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

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3