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调用Orator ORM进行数据库操作

《Python调用OratorORM进行数据库操作》OratorORM是一个功能丰富且灵活的PythonORM库,旨在简化数据库操作,它支持多种数据库并提供了简洁且直观的API,下面我们就... 目录Orator ORM 主要特点安装使用示例总结Orator ORM 是一个功能丰富且灵活的 python O

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

Python Jupyter Notebook导包报错问题及解决

《PythonJupyterNotebook导包报错问题及解决》在conda环境中安装包后,JupyterNotebook导入时出现ImportError,可能是由于包版本不对应或版本太高,解决方... 目录问题解决方法重新安装Jupyter NoteBook 更改Kernel总结问题在conda上安装了

Python如何计算两个不同类型列表的相似度

《Python如何计算两个不同类型列表的相似度》在编程中,经常需要比较两个列表的相似度,尤其是当这两个列表包含不同类型的元素时,下面小编就来讲讲如何使用Python计算两个不同类型列表的相似度吧... 目录摘要引言数字类型相似度欧几里得距离曼哈顿距离字符串类型相似度Levenshtein距离Jaccard相

Python安装时常见报错以及解决方案

《Python安装时常见报错以及解决方案》:本文主要介绍在安装Python、配置环境变量、使用pip以及运行Python脚本时常见的错误及其解决方案,文中介绍的非常详细,需要的朋友可以参考下... 目录一、安装 python 时常见报错及解决方案(一)安装包下载失败(二)权限不足二、配置环境变量时常见报错及