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

2024-08-25 15:20

本文主要是介绍Python酷库之旅-第三方库Pandas(097),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

一、用法精讲

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.NoteThe 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 = Trueallows_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).NoteThe 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 = Trueerrors{‘raise’, ‘ignore’}, default ‘raise’
Control raising of exceptions on invalid data for provided dtype.raise : allow exceptions to be raisedignore : 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、博客个人主页

这篇关于Python酷库之旅-第三方库Pandas(097)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1105917

相关文章

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

Python中re模块结合正则表达式的实际应用案例

《Python中re模块结合正则表达式的实际应用案例》Python中的re模块是用于处理正则表达式的强大工具,正则表达式是一种用来匹配字符串的模式,它可以在文本中搜索和匹配特定的字符串模式,这篇文章主... 目录前言re模块常用函数一、查看文本中是否包含 A 或 B 字符串二、替换多个关键词为统一格式三、提

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re