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快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

python连接本地SQL server详细图文教程

《python连接本地SQLserver详细图文教程》在数据分析领域,经常需要从数据库中获取数据进行分析和处理,下面:本文主要介绍python连接本地SQLserver的相关资料,文中通过代码... 目录一.设置本地账号1.新建用户2.开启双重验证3,开启TCP/IP本地服务二js.python连接实例1.

基于Python和MoviePy实现照片管理和视频合成工具

《基于Python和MoviePy实现照片管理和视频合成工具》在这篇博客中,我们将详细剖析一个基于Python的图形界面应用程序,该程序使用wxPython构建用户界面,并结合MoviePy、Pill... 目录引言项目概述代码结构分析1. 导入和依赖2. 主类:PhotoManager初始化方法:__in

Python从零打造高安全密码管理器

《Python从零打造高安全密码管理器》在数字化时代,每人平均需要管理近百个账号密码,本文将带大家深入剖析一个基于Python的高安全性密码管理器实现方案,感兴趣的小伙伴可以参考一下... 目录一、前言:为什么我们需要专属密码管理器二、系统架构设计2.1 安全加密体系2.2 密码强度策略三、核心功能实现详解

Python Faker库基本用法详解

《PythonFaker库基本用法详解》Faker是一个非常强大的库,适用于生成各种类型的伪随机数据,可以帮助开发者在测试、数据生成、或其他需要随机数据的场景中提高效率,本文给大家介绍PythonF... 目录安装基本用法主要功能示例代码语言和地区生成多条假数据自定义字段小结Faker 是一个 python

Python实现AVIF图片与其他图片格式间的批量转换

《Python实现AVIF图片与其他图片格式间的批量转换》这篇文章主要为大家详细介绍了如何使用Pillow库实现AVIF与其他格式的相互转换,即将AVIF转换为常见的格式,比如JPG或PNG,需要的小... 目录环境配置1.将单个 AVIF 图片转换为 JPG 和 PNG2.批量转换目录下所有 AVIF 图

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

详解如何通过Python批量转换图片为PDF

《详解如何通过Python批量转换图片为PDF》:本文主要介绍如何基于Python+Tkinter开发的图片批量转PDF工具,可以支持批量添加图片,拖拽等操作,感兴趣的小伙伴可以参考一下... 目录1. 概述2. 功能亮点2.1 主要功能2.2 界面设计3. 使用指南3.1 运行环境3.2 使用步骤4. 核