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版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D

Python函数作用域与闭包举例深度解析

《Python函数作用域与闭包举例深度解析》Python函数的作用域规则和闭包是编程中的关键概念,它们决定了变量的访问和生命周期,:本文主要介绍Python函数作用域与闭包的相关资料,文中通过代码... 目录1. 基础作用域访问示例1:访问全局变量示例2:访问外层函数变量2. 闭包基础示例3:简单闭包示例4

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符

Python版本与package版本兼容性检查方法总结

《Python版本与package版本兼容性检查方法总结》:本文主要介绍Python版本与package版本兼容性检查方法的相关资料,文中提供四种检查方法,分别是pip查询、conda管理、PyP... 目录引言为什么会出现兼容性问题方法一:用 pip 官方命令查询可用版本方法二:conda 管理包环境方法

基于Python开发Windows自动更新控制工具

《基于Python开发Windows自动更新控制工具》在当今数字化时代,操作系统更新已成为计算机维护的重要组成部分,本文介绍一款基于Python和PyQt5的Windows自动更新控制工具,有需要的可... 目录设计原理与技术实现系统架构概述数学建模工具界面完整代码实现技术深度分析多层级控制理论服务层控制注

pycharm跑python项目易出错的问题总结

《pycharm跑python项目易出错的问题总结》:本文主要介绍pycharm跑python项目易出错问题的相关资料,当你在PyCharm中运行Python程序时遇到报错,可以按照以下步骤进行排... 1. 一定不要在pycharm终端里面创建环境安装别人的项目子模块等,有可能出现的问题就是你不报错都安装

Python打包成exe常用的四种方法小结

《Python打包成exe常用的四种方法小结》本文主要介绍了Python打包成exe常用的四种方法,包括PyInstaller、cx_Freeze、Py2exe、Nuitka,文中通过示例代码介绍的非... 目录一.PyInstaller11.安装:2. PyInstaller常用参数下面是pyinstal

Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题

《Python爬虫HTTPS使用requests,httpx,aiohttp实战中的证书异步等问题》在爬虫工程里,“HTTPS”是绕不开的话题,HTTPS为传输加密提供保护,同时也给爬虫带来证书校验、... 目录一、核心问题与优先级检查(先问三件事)二、基础示例:requests 与证书处理三、高并发选型:

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数