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

2024-08-25 23:28

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

目录

一、用法精讲

421、pandas.DataFrame.infer_objects方法

421-1、语法

421-2、参数

421-3、功能

421-4、返回值

421-5、说明

421-6、用法

421-6-1、数据准备

421-6-2、代码示例

421-6-3、结果输出

422、pandas.DataFrame.copy方法

422-1、语法

422-2、参数

422-3、功能

422-4、返回值

422-5、说明

422-6、用法

422-6-1、数据准备

422-6-2、代码示例

422-6-3、结果输出

423、pandas.DataFrame.bool方法

423-1、语法

423-2、参数

423-3、功能

423-4、返回值

423-5、说明

423-6、用法

423-6-1、数据准备

423-6-2、代码示例

423-6-3、结果输出

424、pandas.DataFrame.to_numpy方法

424-1、语法

424-2、参数

424-3、功能

424-4、返回值

424-5、说明

424-6、用法

424-6-1、数据准备

424-6-2、代码示例

424-6-3、结果输出

425、pandas.DataFrame.head方法

425-1、语法

425-2、参数

425-3、功能

425-4、返回值 

425-5、说明

425-6、用法

425-6-1、数据准备

425-6-2、代码示例

425-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

421、pandas.DataFrame.infer_objects方法
421-1、语法
# 421、pandas.DataFrame.infer_objects方法
pandas.DataFrame.infer_objects(copy=None)
Attempt to infer better dtypes for object columns.Attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction.Parameters:
copybool, default True
Whether to make a copy for non-object or non-inferable columns or Series.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 = TrueReturns:
same type as input object.
421-2、参数

421-2-1、copy(可选,默认值为None)布尔值,决定是否在执行推断操作时创建数据的副本。如果设置为True,则会返回一个新的DataFrame,其推断后的类型会应用到新的对象上,原始的DataFrame不会被修改;如果设置为False,则推断的类型会直接在原始的DataFrame上进行修改。若设置为None(默认值),函数会决定是否创建副本,这个决定可能依赖于底层实现,通常情况下会在需要时创建副本。

421-3、功能

        用于从数据类型为object的列中推断出更具体的数据类型。例如,如果某一列中实际存储的是整数或浮点数,但由于某些原因被读取为object类型,这个方法就可以尝试将其转化为int64float64类型。

421-4、返回值

        返回一个DataFrame,其object类型的列被尝试推断为更具体的类型,如果copy=True,返回的是一个新的DataFrame;否则,原始DataFrame将被修改并返回。

421-5、说明

        无

421-6、用法
421-6-1、数据准备
421-6-2、代码示例
# 421、pandas.DataFrame.infer_objects方法
import pandas as pd
# 创建一个DataFrame,其中的某些列被推断为object类型
df = pd.DataFrame({'A': [1, 2, 3],'B': [4.0, 5.1, 6.2],'C': ['2022-01-01', '2023-01-01', '2024-01-01']
}, dtype='object')
# 使用infer_objects来推断更具体的类型
df_inferred = df.infer_objects()
print(df_inferred.dtypes)
421-6-3、结果输出
# 421、pandas.DataFrame.infer_objects方法
# A      int64
# B    float64
# C     object
# dtype: object
422、pandas.DataFrame.copy方法
422-1、语法
# 422、pandas.DataFrame.copy方法
pandas.DataFrame.copy(deep=True)
Make a copy of this object’s indices and data.When deep=True (default), a new object will be created with a copy of the calling object’s data and indices. Modifications to the data or indices of the copy will not be reflected in the original object (see notes below).When deep=False, a new object will be created without copying the calling object’s data or index (only references to the data and index are copied). Any changes to the data of the original will be reflected in the shallow copy (and vice versa).NoteThe deep=False behaviour as described above will change in pandas 3.0. Copy-on-Write will be enabled by default, which means that the “shallow” copy is that is returned with deep=False will still avoid making an eager copy, but changes to the data of the original will no longer be reflected in the shallow copy (or vice versa). Instead, it makes use of a lazy (deferred) copy mechanism that will copy the data only when any changes to the original or shallow copy is made.You can already get the future behavior and improvements through enabling copy on write pd.options.mode.copy_on_write = TrueParameters:
deep
bool, default True
Make a deep copy, including a copy of the data and the indices. With deep=False neither the indices nor the data are copied.Returns:
Series or DataFrame
Object type matches caller.NotesWhen deep=True, data is copied but actual Python objects will not be copied recursively, only the reference to the object. This is in contrast to copy.deepcopy in the Standard Library, which recursively copies object data (see examples below).While Index objects are copied when deep=True, the underlying numpy array is not copied for performance reasons. Since Index is immutable, the underlying data can be safely shared and a copy is not needed.Since pandas is not thread safe, see the gotchas when copying in a threading environment.When copy_on_write in pandas config is set to True, the copy_on_write config takes effect even when deep=False. This means that any changes to the copied data would make a new copy of the data upon write (and vice versa). Changes made to either the original or copied variable would not be reflected in the counterpart. See Copy_on_Write for more information.
422-2、参数

422-2-1、deep(可选,默认值为True)布尔值,该参数决定是否执行深复制(deep copy):

  • deep=True(默认值):进行深复制,这意味着副本和原始DataFrame的数据将独立存储,改变副本中的数据不会影响原始DataFrame,反之亦然。
  • deep=False:进行浅复制,这意味着副本和原始DataFrame共享数据存储空间,改变副本中的数据可能会影响原始DataFrame,反之亦然。
422-3、功能

        用于生成现有DataFrame的一个副本,它允许用户选择进行深复制还是浅复制,从而根据需要选择合适的数据复制方式:

  • 深复制(deep copy):创建DataFrame和其数据的完整拷贝,包括数据、索引等,确保副本和原始对象完全独立。
  • 浅复制(shallow copy):创建DataFrame的新引用,但不复制数据本身,因此两者共享相同的底层数据存储空间。
422-4、返回值

        返回一个新的DataFrame对象,对于深复制,这个新对象是对原始DataFrame的完全独立的拷贝;对于浅复制,这个新对象与原始DataFrame共享相同的数据。

422-5、说明

        无

422-6、用法
422-6-1、数据准备
422-6-2、代码示例
# 422、pandas.DataFrame.copy方法
import pandas as pd
# 创建一个DataFrame
df = pd.DataFrame({'A': [1, 2, 3],'B': [4.0, 5.1, 6.2]
})
# 执行深复制(默认行为)
df_deep_copy = df.copy()
df_deep_copy.iloc[0, 0] = 10  # 修改深复制的DataFrame中的数据
print("Original DataFrame:")
print(df)
print("\nDeep Copy DataFrame:")
print(df_deep_copy)
# 执行浅复制
df_shallow_copy = df.copy(deep=False)
df_shallow_copy.iloc[0, 0] = 10  # 修改浅复制的DataFrame中的数据
print("\nOriginal DataFrame after shallow copy modification:")
print(df)
print("\nShallow Copy DataFrame:")
print(df_shallow_copy)
422-6-3、结果输出
# 422、pandas.DataFrame.copy方法
# Original DataFrame:
#    A    B
# 0  1  4.0
# 1  2  5.1
# 2  3  6.2
# 
# Deep Copy DataFrame:
#     A    B
# 0  10  4.0
# 1   2  5.1
# 2   3  6.2
# 
# Original DataFrame after shallow copy modification:
#     A    B
# 0  10  4.0
# 1   2  5.1
# 2   3  6.2
# 
# Shallow Copy DataFrame:
#     A    B
# 0  10  4.0
# 1   2  5.1
# 2   3  6.2
423、pandas.DataFrame.bool方法
423-1、语法
# 423、pandas.DataFrame.bool方法
pandas.DataFrame.bool()
Return the bool of a single element Series or DataFrame.Deprecated since version 2.1.0: bool is deprecated and will be removed in future version of pandas. For Series use pandas.Series.item.This must be a boolean scalar value, either True or False. It will raise a ValueError if the Series or DataFrame does not have exactly 1 element, or that element is not boolean (integer values 0 and 1 will also raise an exception).Returns:
bool
The value in the Series or DataFrame.
423-2、参数

        无

423-3、功能

        用于将DataFrame转换为布尔上下文,但它仅适用于包含单个元素(一个值)的DataFrame。换句话说,只有在DataFrame中包含一个元素的情况下,该方法才会返回该元素的布尔值;否则,它会引发ValueError

423-4、返回值

        如果DataFrame中唯一的元素的布尔值为True,则返回True;否则返回False

423-5、说明

        无

423-6、用法
423-6-1、数据准备
423-6-2、代码示例
# 423、pandas.DataFrame.bool方法
import pandas as pd
# 创建一个包含单个元素的DataFrame
df_single = pd.DataFrame({'A': [True]})
# 将DataFrame转换为布尔值
try:result = df_single.bool()print("The boolean value of the DataFrame is:", result)
except ValueError as e:print('Error:', e)
# 创建一个包含多个元素的DataFrame
df_multiple = pd.DataFrame({'A': [True, False]})
# 尝试将包含多个元素的DataFrame转换为布尔值
try:result = df_multiple.bool()print("The boolean value of the DataFrame is:", result)
except ValueError as e:print('Error:', e)
# 创建一个包含超过一个元素的DataFrame
df_multiple_elements = pd.DataFrame({'A': [5]})
# 尝试将单个非布尔值元素的DataFrame转换为布尔值
try:result = df_multiple_elements.bool()print("The boolean value of the DataFrame is:", result)
except ValueError as e:print('Error:', e)
423-6-3、结果输出
# 423、pandas.DataFrame.bool方法
# The boolean value of the DataFrame is: True
# Error: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
# Error: bool cannot act on a non-boolean single element DataFrame
424、pandas.DataFrame.to_numpy方法
424-1、语法
# 424、pandas.DataFrame.to_numpy方法
panas.DataFrame.to_numpy(dtype=None, copy=False, na_value=_NoDefault.no_default)
Convert the DataFrame to a NumPy array.By default, the dtype of the returned array will be the common NumPy dtype of all types in the DataFrame. For example, if the dtypes are float16 and float32, the results dtype will be float32. This may require copying data and coercing values, which may be expensive.Parameters:
dtype
str or numpy.dtype, optional
The dtype to pass to numpy.asarray().copy
bool, default False
Whether to ensure that the returned value is not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not strictly necessary.na_value
Any, optional
The value to use for missing values. The default value depends on dtype and the dtypes of the DataFrame columns.Returns:
numpy.ndarray
424-2、参数

424-2-1、dtype(可选,默认值为None)指定生成数组的目标数据类型,如果未指定,默认情况下会保留数据的原始类型,可以通过该参数改变所有数据的类型,例如将所有元素转换为浮点型 (float)或整型(int)。

424-2-2、copy(可选,默认值为False)是否强制复制数据,如果设置为False,则在可能的情况下,不会创建数据的副本,而是返回数据的视图(引用);如果设置为True,则始终会复制数据,并返回新的数组。

424-2-3、na_value(可选)在生成的数组中,用于替换缺失值(NaN)的值,如果未指定此参数,缺失值将保留为原来的形式(通常为NaN或者None),指定此参数可以将所有缺失值替换为一个指定的值。

424-3、功能

        将DataFrame中的数据转换并返回为numpy.ndarray,这对于需要进行高效的数值计算和数组操作非常有用。

424-4、返回值

        返回一个numpy.ndarray对象,对象中每个元素对应DataFrame中的值。数据类型、元素值和是否复制数据都取决于传递给该方法的参数。

424-5、说明

        无

424-6、用法
424-6-1、数据准备
424-6-2、代码示例
# 424、pandas.DataFrame.to_numpy方法
import pandas as pd
import numpy as np
# 创建一个示例DataFrame
df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6],'C': [7.1, 8.2, np.nan]
})
# 默认转换为NumPy数组
array_default = df.to_numpy()
print("Default conversion to NumPy array:")
print(array_default)
# 指定数据类型为float32
array_float32 = df.to_numpy(dtype='float32')
print("\nConversion to NumPy array with dtype='float32':")
print(array_float32)
# 强制复制数据
array_copy = df.to_numpy(copy=True)
print("\nConversion to NumPy array with copy=True:")
print(array_copy)
# 替换缺失值NaN为0
array_na_value = df.to_numpy(na_value=0)
print("\nConversion to NumPy array with na_value=0:")
print(array_na_value)
424-6-3、结果输出
# 424、pandas.DataFrame.to_numpy方法
# Default conversion to NumPy array:
# [[1.  4.  7.1]
#  [2.  5.  8.2]
#  [3.  6.  nan]]
# 
# Conversion to NumPy array with dtype='float32':
# [[1.  4.  7.1]
#  [2.  5.  8.2]
#  [3.  6.  nan]]
# 
# Conversion to NumPy array with copy=True:
# [[1.  4.  7.1]
#  [2.  5.  8.2]
#  [3.  6.  nan]]
# 
# Conversion to NumPy array with na_value=0:
# [[1.  4.  7.1]
#  [2.  5.  8.2]
#  [3.  6.  0. ]]
425、pandas.DataFrame.head方法
425-1、语法
# 425、pandas.DataFrame.head方法
pandas.DataFrame.head(n=5)
Return the first n rows.This function returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it.For negative values of n, this function returns all rows except the last |n| rows, equivalent to df[:n].If n is larger than the number of rows, this function returns all rows.Parameters:
n
int, default 5
Number of rows to select.Returns:
same type as caller
The first n rows of the caller object.
425-2、参数

425-2-1、n(可选,默认值为5)整数,指定返回的行数,如果未提供,该方法默认返回前5行。

425-3、功能

        用于返回一个DataFrame的前n行,默认返回前5行,这在预览数据内容时非常有用,特别是当你想要查看一个DataFrame的前几行以便了解数据的结构和内容时。

425-4、返回值 

        返回一个pandas.DataFrame对象,对象包含前n行。

425-5、说明

425-5-1、数据预览:当读入一个新的数据集时,快速查看前几行数据。

425-5-2、调试和检查:在数据处理过程中的不同步骤,检查中间数据的内容和格式。

425-5-3、报告和展示:在展示数据时,只需要展示前几行数据以保持简洁和清晰。

425-6、用法
425-6-1、数据准备
425-6-2、代码示例
# 425、pandas.DataFrame.head方法
import pandas as pd
# 创建一个示例DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace'],'Age': [24, 30, 22, 25, 29, 32, 27],'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'Philadelphia', 'San Antonio']
}
df = pd.DataFrame(data)
# 使用head方法查看前5行
print("前5行:")
print(df.head())
# 使用head方法查看前3行
print("\n前3行:")
print(df.head(n=3))
425-6-3、结果输出
# 425、pandas.DataFrame.head方法
# 前5行:
#       Name  Age         City
# 0    Alice   24     New York
# 1      Bob   30  Los Angeles
# 2  Charlie   22      Chicago
# 3    David   25      Houston
# 4      Eve   29      Phoenix
# 
# 前3行:
#       Name  Age         City
# 0    Alice   24     New York
# 1      Bob   30  Los Angeles
# 2  Charlie   22      Chicago

二、推荐阅读

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

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


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

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用