Python酷库之旅-第三方库Pandas(097)

news2024/9/21 20:46:28

目录

一、用法精讲

416、pandas.DataFrame.memory_usage方法

416-1、语法

416-2、参数

416-3、功能

416-4、返回值

416-5、说明

416-6、用法

416-6-1、数据准备

416-6-2、代码示例

416-6-3、结果输出

417、pandas.DataFrame.empty属性

417-1、语法

417-2、参数

417-3、功能

417-4、返回值

417-5、说明

417-6、用法

417-6-1、数据准备

417-6-2、代码示例

417-6-3、结果输出

418、pandas.DataFrame.set_flags方法

418-1、语法

418-2、参数

418-3、功能

418-4、返回值

418-5、说明

418-6、用法

418-6-1、数据准备

418-6-2、代码示例

418-6-3、结果输出

419、pandas.DataFrame.astype方法

419-1、语法

419-2、参数

419-3、功能

419-4、返回值

419-5、说明

419-6、用法

419-6-1、数据准备

419-6-2、代码示例

419-6-3、结果输出

420、pandas.DataFrame.convert_dtypes方法

420-1、语法

420-2、参数

420-3、功能

420-4、返回值

420-5、说明

420-6、用法

420-6-1、数据准备

420-6-2、代码示例

420-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

416、pandas.DataFrame.memory_usage方法
416-1、语法
# 416、pandas.DataFrame.memory_usage方法
pandas.DataFrame.memory_usage(index=True, deep=False)
Return the memory usage of each column in bytes.

The memory usage can optionally include the contribution of the index and elements of object dtype.

This value is displayed in DataFrame.info by default. This can be suppressed by setting pandas.options.display.memory_usage to False.

Parameters:
index
bool, default True
Specifies whether to include the memory usage of the DataFrame’s index in returned Series. If index=True, the memory usage of the index is the first item in the output.

deep
bool, default False
If True, introspect the data deeply by interrogating object dtypes for system-level memory consumption, and include it in the returned values.

Returns:
Series
A Series whose index is the original column names and whose values is the memory usage of each column in bytes.
416-2、参数

416-2-1、index(可选,默认值为True)布尔值,指定是否包括行索引在内存使用的计算中,如果为True,则行索引所占的内存也会被计算在内;如果为False,则只计算列的内存使用。

416-2-2、deep(可选,默认值为False)布尔值,如果为True,将进行更深入的内存使用分析,这意味着它会对对象类型的列进行更详细的内存消耗计算,尤其是字符串类型的列,默认为False,这时只返回基本的内存使用量。

416-3、功能

        帮助你了解DataFrame的内存使用情况,从而进行性能优化和资源管理。

416-4、返回值

        返回一个Series对象,其中索引为DataFrame的列名(以及行索引,如果index=True),值为相应列(和行索引)的内存使用量(以字节为单位),如果deep=True,则返回的值将更准确地反映对象的内存消费。

416-5、说明

        无

416-6、用法
416-6-1、数据准备
416-6-2、代码示例
# 416、pandas.DataFrame.memory_usage方法
import pandas as pd
# 创建一个DataFrame
data = {
    'A': [1, 2, 3],
    'B': ['foo', 'bar', 'baz'],
    'C': [4.5, 5.5, 6.5]
}
df = pd.DataFrame(data)
# 获取内存使用情况,包括行索引
memory_usage_inclusive = df.memory_usage(index=True)
# 获取内存使用情况,不包括行索引
memory_usage_exclusive = df.memory_usage(index=False)
# 深度计算内存使用情况
deep_memory_usage = df.memory_usage(deep=True)
print("内存使用(包括索引):\n", memory_usage_inclusive)
print("\n内存使用(不包括索引):\n", memory_usage_exclusive)
print("\n深度内存使用:\n", deep_memory_usage)
416-6-3、结果输出
# 416、pandas.DataFrame.memory_usage方法
# 内存使用(包括索引):
#  Index    132
# A         24
# B         24
# C         24
# dtype: int64
# 
# 内存使用(不包括索引):
#  A    24
# B    24
# C    24
# dtype: int64
# 
# 深度内存使用:
#  Index    132
# A         24
# B        180
# C         24
# dtype: int64
417、pandas.DataFrame.empty属性
417-1、语法
# 417、pandas.DataFrame.empty属性
pandas.DataFrame.empty
Indicator whether Series/DataFrame is empty.

True if Series/DataFrame is entirely empty (no items), meaning any of the axes are of length 0.

Returns:
bool
If Series/DataFrame is empty, return True, if not return False.
417-2、参数

        无

417-3、功能

        用于检查一个DataFrame是否为空。具体来说,它用于判断DataFrame是否没有任何数据(即没有行),返回一个布尔值。

417-4、返回值

        返回True如果DataFrame没有任何行;返回False如果DataFrame至少有一行数据。

417-5、说明

        无

417-6、用法
417-6-1、数据准备
417-6-2、代码示例
# 417、pandas.DataFrame.empty属性
import pandas as pd
# 创建一个空的DataFrame
empty_df = pd.DataFrame()
# 创建一个非空的DataFrame
data = {
    'A': [1, 2, 3],
    'B': ['foo', 'bar', 'baz'],
}
non_empty_df = pd.DataFrame(data)
# 检查是否为空
print("empty_df是否为空:", empty_df.empty)
print("non_empty_df是否为空:", non_empty_df.empty)
417-6-3、结果输出
# 417、pandas.DataFrame.empty属性
# empty_df是否为空: True
# non_empty_df是否为空: False
418、pandas.DataFrame.set_flags方法
418-1、语法
# 418、pandas.DataFrame.set_flags方法
pandas.DataFrame.set_flags(*, copy=False, allows_duplicate_labels=None)
Return a new object with updated flags.

Parameters:
copybool, default False
Specify if a copy of the object should be made.

Note

The copy keyword will change behavior in pandas 3.0. Copy-on-Write will be enabled by default, which means that all methods with a copy keyword will use a lazy copy mechanism to defer the copy and ignore the copy keyword. The copy keyword will be removed in a future version of pandas.

You can already get the future behavior and improvements through enabling copy on write pd.options.mode.copy_on_write = True

allows_duplicate_labelsbool, optional
Whether the returned object allows duplicate labels.

Returns:
Series or DataFrame
The same type as the caller.
418-2、参数

418-2-1、copy(可选,默认值为False)布尔值,是否创建一个新的DataFrame副本,如果设置为True,会返回一个新的DataFrame副本;如果为False,则返回原始DataFrame(只会更改标志属性)。

418-2-2、allows_duplicate_labels(可选,默认值为None)布尔值,用于指示是否允许重复标签,如果设置为True,那么DataFrame可以有重复的行或列标签;如果设置为False,则不允许重复标签;如果设置为None,将保持当前状态不变。

418-3、功能

        允许你设置特定的标志,如复制行为和是否允许重复标签,这些标志有助于控制DataFrame的一些基本特性和运行时行为。

418-4、返回值

        返回一个新的DataFrame(如果copy=True),或返回原始DataFrame的视图(如果copy=False),并更新了设置的标志属性。

418-5、说明

        无

418-6、用法
418-6-1、数据准备
418-6-2、代码示例
# 418、pandas.DataFrame.set_flags方法
import pandas as pd
# 创建一个DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6]
})
# 设置allows_duplicate_labels为True
new_df = df.set_flags(allows_duplicate_labels=True)
# 查看标志
print(df.flags.allows_duplicate_labels)
print(new_df.flags.allows_duplicate_labels)
# 通过设置copy=True来创建一个新的DataFrame副本
copy_df = df.set_flags(copy=True)
# 检查副本
print(copy_df is df)  
418-6-3、结果输出
# 418、pandas.DataFrame.set_flags方法
# True
# True
# False
419、pandas.DataFrame.astype方法
419-1、语法
# 419、pandas.DataFrame.astype方法
pandas.DataFrame.astype(dtype, copy=None, errors='raise')
Cast a pandas object to a specified dtype dtype.

Parameters:
dtypestr, data type, Series or Mapping of column name -> data type
Use a str, numpy.dtype, pandas.ExtensionDtype or Python type to cast entire pandas object to the same type. Alternatively, use a mapping, e.g. {col: dtype, …}, where col is a column label and dtype is a numpy.dtype or Python type to cast one or more of the DataFrame’s columns to column-specific types.

copybool, default True
Return a copy when copy=True (be very careful setting copy=False as changes to values then may propagate to other pandas objects).

Note

The copy keyword will change behavior in pandas 3.0. Copy-on-Write will be enabled by default, which means that all methods with a copy keyword will use a lazy copy mechanism to defer the copy and ignore the copy keyword. The copy keyword will be removed in a future version of pandas.

You can already get the future behavior and improvements through enabling copy on write pd.options.mode.copy_on_write = True

errors{‘raise’, ‘ignore’}, default ‘raise’
Control raising of exceptions on invalid data for provided dtype.

raise : allow exceptions to be raised

ignore : suppress exceptions. On error return original object.

Returns:
same type as caller.
419-2、参数

419-2-1、dtype(必须)描述要转换的目标数据类型,可以是单个数据类型(如float、int、str等)或一个字典,字典的键是列名,值是对应的目标数据类型。如果只针对单个列,可以使用一个字符串表示数据类型。

419-2-2、copy(可选,默认值为None)布尔值,指示是否创建一个新的DataFrame副本,如果设置为True,则会强制创建一个新副本;如果为False,则会尝试在可能的情况下直接在原DataFrame上进行更改。

419-2-3、errors(可选,默认值为'raise')字符串,定义在数据类型转换过程中发生错误时的行为。

  • 'raise':发生错误时引发异常。
  • 'ignore':发生错误时返回原始数据,不进行转换。
419-3、功能

        用于转换DataFrame中数据类型的方法,通过该方法,你可以将DataFrame的列转换为指定的数据类型。

419-4、返回值

        返回一个新的DataFrame,其中数据类型已被转换为指定的类型。

419-5、说明

        无

419-6、用法
419-6-1、数据准备
419-6-2、代码示例
# 419、pandas.DataFrame.astype方法
import pandas as pd
# 创建一个DataFrame
df = pd.DataFrame({
    'A': ['1', '2', '3'],
    'B': ['4.0', '5.1', '6.2']
})
# 查看原始数据类型
print(df.dtypes)
# 将列A转换为整数,将列B转换为浮点数
df_converted = df.astype({'A': 'int', 'B': 'float'})
# 查看转换后的数据类型
print(df_converted.dtypes)
# 打印转换后的数据
print(df_converted)
419-6-3、结果输出
# 419、pandas.DataFrame.astype方法
# A    object
# B    object
# dtype: object
# A      int32
# B    float64
# dtype: object
#    A    B
# 0  1  4.0
# 1  2  5.1
# 2  3  6.2
420、pandas.DataFrame.convert_dtypes方法
420-1、语法
# 420、pandas.DataFrame.convert_dtypes方法
pandas.DataFrame.convert_dtypes(infer_objects=True, convert_string=True, convert_integer=True, convert_boolean=True, convert_floating=True, dtype_backend='numpy_nullable')
Convert columns to the best possible dtypes using dtypes supporting pd.NA.

Parameters:
infer_objectsbool, default True
Whether object dtypes should be converted to the best possible types.

convert_stringbool, default True
Whether object dtypes should be converted to StringDtype().

convert_integerbool, default True
Whether, if possible, conversion can be done to integer extension types.

convert_booleanbool, defaults True
Whether object dtypes should be converted to BooleanDtypes().

convert_floatingbool, defaults True
Whether, if possible, conversion can be done to floating extension types. If convert_integer is also True, preference will be give to integer dtypes if the floats can be faithfully casted to integers.

dtype_backend{‘numpy_nullable’, ‘pyarrow’}, default ‘numpy_nullable’
Back-end data type applied to the resultant DataFrame (still experimental). Behaviour is as follows:

"numpy_nullable": returns nullable-dtype-backed DataFrame (default).

"pyarrow": returns pyarrow-backed nullable ArrowDtype DataFrame.

New in version 2.0.

Returns:
Series or DataFrame
Copy of input object with new dtype.
420-2、参数

420-2-1、infer_objects(可选,默认值为True)布尔值,指示是否对object类型列进行类型推断,如果为True,则会尝试将那些可以转换为其他类型的对象列转换为更具体的数据类型。

420-2-2、convert_string(可选,默认值为True)布尔值,指示是否将具有字符串数据的列转换为StringDtype,如果为True,将会把包含字符串的object列转换为更具表现力的字符串类型。

420-2-3、convert_integer(可选,默认值为True)布尔值,指示是否将能够转换为整数的列转换为相应的整数类型,通过此设置,可以将数据中的整数以更合适的格式进行保存。

420-2-4、convert_boolean(可选,默认值为True)布尔值,指示是否将布尔列转换为BooleanDtype,如果为True,布尔值将被转换为支持缺失值的布尔类型。

420-2-5、convert_floating(可选,默认值为True)布尔值,指示是否将能够转换为浮动数据的列转换为适当的浮点类型,如果为True,浮点数将被转换为支持缺失值的浮点类型。

420-2-6、dtype_backend(可选,默认值为'numpy_nullable')字符串,指定使用的数据类型后端,可以选择'numpy_nullable'或'pyarrow',这决定了在转换数据时底层使用的类型支持。

420-3、功能

        用于自动推断并转换DataFrame中的列数据类型,以便于后续的数据处理和分析,此方法旨在提供更灵活的类型支持,尤其在处理缺失值和兼容性方面。

420-4、返回值

        返回一个新的DataFrame,其中的数据类型被转换为更适合的类型,如果DataFrame中的列可以被转换为更具体的类型,则会在返回的DataFrame中体现出来。

420-5、说明

        无

420-6、用法
420-6-1、数据准备
420-6-2、代码示例
# 420、pandas.DataFrame.convert_dtypes方法
import pandas as pd
import numpy as np
# 创建一个DataFrame
df = pd.DataFrame({
    'A': ['1', '2', '3', None],           # 包含缺失值
    'B': [4.0, 5.1, 6.2, np.nan],          # 包含缺失值
    'C': [True, False, None, True]         # 布尔列,包含缺失值
})
# 查看原始数据类型
print(df.dtypes)
# 转换数据类型
df_converted = df.convert_dtypes()
# 查看转换后的数据类型
print(df_converted.dtypes)
# 打印转换后的数据
print(df_converted)
420-6-3、结果输出
# 420、pandas.DataFrame.convert_dtypes方法
# A     object
# B    float64
# C     object
# dtype: object
# A    string[python]
# B           Float64
# C           boolean
# dtype: object
#       A     B      C
# 0     1   4.0   True
# 1     2   5.1  False
# 2     3   6.2   <NA>
# 3  <NA>  <NA>   True

二、推荐阅读

1、Python筑基之旅
2、Python函数之旅
3、Python算法之旅
4、Python魔法之旅
5、博客个人主页

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2072149.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

AI大模型日报#0825:10行代码让大模型数学提升20%、文心日均调用超6亿

导读&#xff1a;AI大模型日报&#xff0c;爬虫LLM自动生成&#xff0c;一文览尽每日AI大模型要点资讯&#xff01;目前采用“文心一言”&#xff08;ERNIE-4.0-8K-latest&#xff09;、“智谱AI”&#xff08;glm-4-0520&#xff09;生成了今日要点以及每条资讯的摘要。欢迎阅…

Reinforcement-Learning 1.fundamental concept

1.首先用一个网格世界来理解 机器人在网格世界行走有四种形式&#xff0c;Accessible/forbidden/target cells, boundary. 提出一个任务&#xff0c;找到一个good的方式去到target 什么是good&#xff0c;不碰到boundary不进入forbidden最短的道路进入target 2.state State…

UE基础 —— 打包项目

目录 设置游戏的默认地图 创建打包文件 发布 签名和加密 内容烘焙 优化加载时间 使用事件驱动加载器&#xff08;Event Driven Loader&#xff0c;EDL&#xff09;和异步加载线程&#xff08;Asynchronous Loading Thread&#xff0c;ALT&#xff09; 压缩.pak文件 对…

PG数据库导致断电/重启无法正常启动

一、问题 数据库断电后&#xff0c;启动PG数据库后无法正常启动&#xff0c;报”psql: could not connect to server: No such file or directory”的错误&#xff0c;错误图片如下&#xff1a; 二、背景分析 数据库是单机版&#xff0c;使用k8s进行部署运行在指定节点&#…

华为OD机试-找座位(C++ Java Python)

题目描述: 在一个大型体育场内举办了一场大型活动&#xff0c;由于疫情防控的需要&#xff0c;要求每位观众的必须间隔至少一个空位才允许落座。现在给出一排观众座位 分布图&#xff0c;座位中存在已落座的观众&#xff0c;请计算出&#xff0c;在不移动现有观众座位的情况下&…

正则表达式匹配——力扣困难题解

力扣链接&#xff1a;正则表达式匹配 题目描述&#xff1a; 给你一个字符串 s 和一个字符规律 p&#xff0c;请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。 ‘.’ 匹配任意单个字符 ‘*’ 匹配零个或多个前面的那一个元素 所谓匹配&#xff0c;是要涵盖 整个 字符串 …

GUI界面开发之tkinter(三) 按钮类组件和选择列表类组件

大家好&#xff01;我是码银儿~&#xff0c;欢迎关注&#x1f970;&#xff1a; CSDN&#xff1a;码银公众号&#xff1a;码银学编程 一、按钮类组件 按钮类组件顾名思义就是按钮&#xff0c;跟平时大家看见的按钮没啥区别&#xff0c;允许用户通过点击执行操作。以下是三种…

Awesome-LLMs-for-Video-Understanding - 基于大型语言模型的视频理解研究

Awesome-LLMs-for-Video-Understanding 是 基于大型语言模型的视频理解研究 github : https://github.com/yunlong10/Awesome-LLMs-for-Video-Understandingpaper&#xff1a;Video Understanding with Large Language Models: A Survey https://arxiv.org/pdf/2312.17432 视频…

五、前后端分离通用权限系统(5)

&#x1f33b;&#x1f33b; 目录 一、前端框架1.1、vue-element-admin1.1.1、Vue 概述1.1.2、Element-ui 概述1.1.3、ES6 概述 1.2、vue-admin-template1.2.1、简介1.2.2、下载1.2.3、安装1.2.4、源码目录结构&#xff08;了解&#xff09;1.2.5、改造登录&退出功能1.2.5.…

跨域解决 | 面试常问问题

跨域解决 | 面试常问问题 跨域问题一直是前端开发中不可避免的一部分&#xff0c;它涉及到浏览器的同源策略和安全机制。本文将深入解析跨域问题的本质&#xff0c;并探讨前端和后端的多种解决方案&#xff0c;同时分享一些扩展与高级技巧。最后&#xff0c;我们还将总结跨域解…

K8S系列——(二)、K8S部署RocketMQ集群

1、环境准备 要将RocketMQ部署到K8S上&#xff0c;首先你需要提前准备一个K8S集群环境&#xff0c;如图我已经准备好了一个版本为 v1.28.13 的 K8S 集群&#xff08;其他版本也没问题&#xff09;&#xff1a; 角色IPMaster192.168.6.220Node-1192.168.6.221Node-2192.168.6.…

浏览器不开梯子无法上网,检查代理或防火墙或者找不到服务器ip地址

1、代理没有关闭 检查代理是否关闭 检查方法1&#xff1a; 在控制面版中找到Internet选项&#xff0c;点击连接栏&#xff0c;在连接栏中选择局域网设置。之后将代理服务器下面的框选中的对勾取消。最终如下 检查方法2&#xff1a; 打开设置&#xff0c;找到网络和internet…

书生浦语大模型实战营:LMDeploy量化部署

1.任务&#xff1a; 使用结合W4A16量化与kv cache量化的internlm2_5-1_8b-chat模型封装本地API并与大模型进行一次对话。 2.背景&#xff1a; 1.计算模型需要的权重大小&#xff1a; 1B代表10个亿参数&#xff0c;假如是16位浮点数&#xff08;f16&#xff09;&#xff0c;也…

计算机视觉概念科普

计算机视觉&#xff08;Computer Vision, CV&#xff09;是一门多学科交叉的科学&#xff0c;旨在让计算机具备“看”的能力&#xff0c;即通过图像或视频数据来理解世界。它结合了信号处理、图像处理、模式识别、机器学习等多个领域的技术&#xff0c;让计算机能够执行诸如识别…

【Python学习手册(第四版)】学习笔记20.2-迭代和解析(二)-迭代解析、迭代方法的计时比较、函数陷阱

个人总结难免疏漏&#xff0c;请多包涵。更多内容请查看原文。本文以及学习笔记系列仅用于个人学习、研究交流。 本文较简单&#xff0c;主要是概括了解析语法&#xff08;列表解析、生成器、集合、字典解析&#xff09;&#xff0c;以及对前面的各种迭代进行计时比较&#xf…

通过python解决原神解密

最近楼主玩原神世界任务做到稻妻了&#xff0c;在稻妻有很多解密游戏&#xff0c;但是博主最头疼的就是稻妻的石头解密QAQ&#xff08;如图&#xff09; 就在昨晚&#xff0c;楼主又碰到了石头解密&#xff0c;瞎打&#xff0c;半天解不出来。于是就想&#xff0c;有没有什么严…

如何在Windows下使用make编译Makefile

最近有小伙伴咨询我去编译运行一个程序。我一开始以为是CMakeLists&#xff0c;结果发现是makefile。 什么是Makefile ‌Makefile是一种用于自动化构建和管理程序的工具‌&#xff0c;它定义了项目中文件的依赖关系和构建步骤&#xff0c;帮助程序员自动化编译、链接和打包程序…

Ps:创建帧动画

在 Photoshop 中&#xff0c;帧动画 Frame Animation是一种通过在“时间轴”面板中创建和管理多个帧来实现动画效果的方式。 所谓帧动画&#xff0c;也就是传统意义上的逐帧动画&#xff0c;依次播放每个帧而构成的动画形式。每个帧记录了“图层”面板上所有图层的属性状态&…

QT Mainwindow下指定控件的setMouseTracking(true)和mousemoveevent函数失效-问题解决

目录&#xff1a; 一&#xff0c;问题描述二&#xff0c;解决方法2.1解决依据2.2方法实操 三&#xff0c;参考资料 一&#xff0c;问题描述 ☀️之前碰到过的一个问题&#xff0c;现在分享出来&#xff1a;想在qt哪里搞个鼠标移动在控件显示的图片上&#xff0c;然后实时显示对…

[数据集][目标检测]红外场景下车辆和行人检测数据集VOC+YOLO格式19069张4类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;19069 标注数量(xml文件个数)&#xff1a;19069 标注数量(txt文件个数)&#xff1a;19069 标…