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

目录

一、用法精讲

pandas.DataFrame.to_csv%E5%87%BD%E6%95%B0-toc" style="margin-left:120px;">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、结果输出

pandas.DataFrame.empty%E5%B1%9E%E6%80%A7-toc" style="margin-left:120px;">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、结果输出

pandas.DataFrame.set_flags%E6%96%B9%E6%B3%95-toc" style="margin-left:120px;">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、结果输出

pandas.DataFrame.astype%E6%96%B9%E6%B3%95-toc" style="margin-left:120px;">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、结果输出

pandas.DataFrame.convert_dtypes%E6%96%B9%E6%B3%95-toc" style="margin-left:120px;">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、博客个人主页

一、用法精讲

pandas.DataFrame.to_csv%E5%87%BD%E6%95%B0">416、pandas.DataFrame.memory_usage方法
416-1、语法
python"># 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、数据准备
python">无
416-6-2、代码示例
python"># 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、结果输出
python"># 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
pandas.DataFrame.empty%E5%B1%9E%E6%80%A7">417、pandas.DataFrame.empty属性
417-1、语法
python"># 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、数据准备
python">无
417-6-2、代码示例
python"># 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、结果输出
python"># 417、pandas.DataFrame.empty属性
# empty_df是否为空: True
# non_empty_df是否为空: False
pandas.DataFrame.set_flags%E6%96%B9%E6%B3%95">418、pandas.DataFrame.set_flags方法
418-1、语法
python"># 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、数据准备
python">无
418-6-2、代码示例
python"># 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、结果输出
python"># 418、pandas.DataFrame.set_flags方法
# True
# True
# False
pandas.DataFrame.astype%E6%96%B9%E6%B3%95">419、pandas.DataFrame.astype方法
419-1、语法
python"># 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、数据准备
python">无
419-6-2、代码示例
python"># 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、结果输出
python"># 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
pandas.DataFrame.convert_dtypes%E6%96%B9%E6%B3%95">420、pandas.DataFrame.convert_dtypes方法
420-1、语法
python"># 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、数据准备
python">无
420-6-2、代码示例
python"># 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、结果输出
python"># 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.ppmy.cn/news/1515553.html

相关文章

如何使用 vue2+element-ui 处理复杂表单,避免单文件过大的问题

引言 在工作中我经常需要处理一些复杂、动态表单&#xff0c;但是随着需求不断迭代&#xff0c;我们也许会发现曾经两三百行的.vue文件现在不知不觉到了两千行&#xff0c;三千行&#xff0c;甚至更多... 这对于一个需要长期维护的项目&#xff0c;无疑是增加了很多难度。 因此…

乐鑫ESP32-C2物联网芯片,助力家居设备智能升级,高效能连接方案

随着物联网技术的飞速发展&#xff0c;智能家居设备正逐渐成为现代生活的一部分。从智能灯泡到智能安防系统&#xff0c;这些设备通过无缝的网络连接&#xff0c;让家庭变得更加智能和便捷。 想象一下&#xff0c;当你下班回家&#xff0c;智能门锁识别你的身份自动解锁&#…

Spring 中FileSystemXmlApplicationContext

FileSystemXmlApplicationContext 是 Spring Framework 中的一个重要类&#xff0c;位于 org.springframework.context.support 包中。它是 ApplicationContext 接口的实现&#xff0c;专门用于从文件系统中的 XML 配置文件加载 Spring bean 定义。与 ClassPathXmlApplicationC…

如何把huggingface格式的whisper模型转为openai格式

1. 摘要 openai目前提供的模型有tiny&#xff0c;tiny.en&#xff0c;base&#xff0c;base.en&#xff0c;small&#xff0c;small.en&#xff0c;medium&#xff0c;medium.en&#xff0c;large-v1&#xff0c;large-v2&#xff0c;large-v3共11种&#xff0c;其中en结尾的是…

Resilience4J服务熔断隔离与限流

为了保障文章的流畅性&#xff08;文章穿插大量的环境搭建没意思&#xff0c;会干扰文章的主题&#xff0c;无聊的很&#xff09;&#xff0c;将环境的搭建与测试&#xff0c;工具的版本说明放了文末&#xff1a; 六、环境搭建。 一、Circuit Breaker是什么 1.1、官网 https…

@RequestBody与@RequestParam:Spring MVC中的参数接收差异解析

在Spring MVC中&#xff0c;RequestBody和RequestParam是两个常用于接收客户端请求参数的注解&#xff0c;但它们的使用场景和作用机制存在显著差异。了解这些差异对于开发RESTful API和处理HTTP请求至关重要。本文将详细探讨RequestBody与RequestParam的区别。 RequestParam …

matlab与VS混合编程以及错误解决

目录 前言&#xff1a; 1. matlab打包生成dll文件 打包方法一&#xff1a; 打包方法二&#xff1a; 2. VS端配置 3. 代码测试 4. 错误解决 a. 1.0x0000000000000000 处有未经处理的异常(在 Project1.exe 中): 0xC0000005: 执行位置 0x0000000000000000 时发生访问冲突。…

从法律风险的角度来看,项目经理遇到不清楚或不明确问题时的处理

大家好&#xff0c;我是不会魔法的兔子&#xff0c;在北京从事律师工作&#xff0c;日常分享项目管理风险预防方面的内容。 序言 在项目开展过程中&#xff0c;有时候会遇到一些不清楚或不明确的状况&#xff0c;但碍于项目进度的紧迫性&#xff0c;不得不硬着头皮做决策&…

数据结构(邓俊辉)学习笔记】串 02——模式匹配

1. 问题与需求 好&#xff0c;接下来我们就对这一章的主角&#xff0c;也就是串匹配问题&#xff0c;作一概述。 包括这个问题是什么&#xff1f;有哪些不同层次的功能要求&#xff1f;以及如何评测相应算法的性能&#xff0c;尽管我们还没有涉及到具体的算法。 如果你使用…

【WebSocket】websocket学习【二】

1.需求&#xff1a;通过websocket实现在线聊天室 2.流程分析 3.消息格式 客户端 --> 服务端 {"toName":"张三","message":"你好"}服务端 --> 客户端 系统消息格式&#xff1a;{"system":true,"fromName"…

Python——xml.etree.ElementTree

Python的xml.etree.ElementTree库详解 xml.etree.ElementTree&#xff08;简称ElementTree&#xff09;是Python标准库中用于处理XML文件的模块。它提供了简洁且高效的API&#xff0c;适用于解析、创建和修改XML文档。在需要处理XML数据的场景中&#xff0c;比如配置文件、数据…

npm install报错解决记录

npm install报错解决记录 在前端开发和Node.js项目中&#xff0c;npm install 是我们日常工作中频繁使用的命令之一&#xff0c;它用于安装项目所需的依赖包。然而&#xff0c;在实际操作中&#xff0c;我们经常会遇到各种各样的错误&#xff0c;这些错误可能源于网络问题、np…

【Apache Doris】周FAQ集锦:第 19 期

【Apache Doris】周FAQ集锦&#xff1a;第 19 期 SQL问题数据操作问题运维常见问题其它问题关于社区 欢迎查阅本周的 Apache Doris 社区 FAQ 栏目&#xff01; 在这个栏目中&#xff0c;每周将筛选社区反馈的热门问题和话题&#xff0c;重点回答并进行深入探讨。旨在为广大用户…

Hadoop的概念

目录 1.什么是大数据 2.Hadoop体系结构 1&#xff1a;HDFS&#xff08;Hadoop Distributed File System&#xff09; 2 &#xff1a;MapReduce 3&#xff1a;YARN&#xff08;Yet Another Resource Negotiator&#xff09; 3、Hadoop生态圈 4、MapReduce的原理和工作流程…

Cloudflare+Nginx+Docker搭建可用Docker镜像源,解决Docker镜像源失效问题。(保姆级教程)

1. 前提准备条件&#xff08;中转机&#xff09; 准备一个域名。 一台能访问国际互联网服务器,充当中转站&#xff08;最好就是流量大的&#xff09;。 注册一个Coudflare账号&#xff0c;通过Coudflare解析域名&#xff08;DNS&#xff09;到服务器IP&#xff0c;开启CDN&am…

第四十六篇,PID心法解读

猛回头&#xff0c;有近半年的时光没输出了&#xff0c;看着昨天加班调的PID数据&#xff0c;灵光闪现了一下&#xff0c;赶紧记录。 参数整定找最佳&#xff0c;从小到大顺序查   先是比例后积分&#xff0c;最后再把微分加 曲线振荡很频繁&#xff0c;比例度盘要放大   曲…

OpenCV c++ 实现图像马赛克效果

VS2022配置OpenCV环境 关于OpenCV在VS2022上配置的教程可以参考&#xff1a;VS2022 配置OpenCV开发环境详细教程 图像马赛克 图像马赛克&#xff08;Image Mosaic&#xff09;的原理基于将图像的特定区域替换为像素块&#xff0c;这些像素块可以是纯色或者平均色&#xff0c…

通过建模走出人工智能寒冬

很多人对 GenAI 是否会产生商业影响持怀疑态度&#xff0c;但我认为他们不仅错了&#xff0c;而且犯了 2001 年人们在互联网上犯下的错误。他们认为硅谷的炒作是无稽之谈&#xff0c;因此其背后的想法也是无稽之谈。 这是很危险的&#xff0c;我认为&#xff0c;这比大多数零售…

MessageDialog 是 Qt Quick Controls 中的一个组件,用于显示消息对话框

MessageDialog 是 Qt Quick Controls 中的一个组件&#xff0c;用于显示消息对话框。它提供了一个简单的方法来提示用户并获取他们的响应。下面是 MessageDialog 的详解&#xff0c;包括用法和常见属性。 1. 基本用法 import QtQuick 2.15 import QtQuick.Controls 2.15Appli…

LabVIEW多显示器环境下主显示器识别与管理

该程序使用 LabVIEW 图形化编程语言&#xff0c;涉及多显示器环境中主显示器的识别与信息提取。图像显示了两个不同的方法来获取主显示器的信息。 第一部分&#xff1a;方法一——基于显示器位置的主显示器识别 1. 当前监视器识别&#xff1a; 使用“FP.Monitor”属性节点获取…