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

2024-08-27 09:36

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

目录

一、用法精讲

441、pandas.DataFrame.mask方法

441-1、语法

441-2、参数

441-3、功能

441-4、返回值

441-5、说明

441-6、用法

441-6-1、数据准备

441-6-2、代码示例

441-6-3、结果输出

442、pandas.DataFrame.query方法

442-1、语法

442-2、参数

442-3、功能

442-4、返回值

442-5、说明

442-6、用法

442-6-1、数据准备

442-6-2、代码示例

442-6-3、结果输出

443、pandas.DataFrame.__add__魔法方法

443-1、语法

443-2、参数

443-3、功能

443-4、返回值

443-5、说明

443-6、用法

443-6-1、数据准备

443-6-2、代码示例

443-6-3、结果输出

444、pandas.DataFrame.add方法

444-1、语法

444-2、参数

444-3、功能

444-4、返回值

444-5、说明

444-6、用法

444-6-1、数据准备

444-6-2、代码示例

444-6-3、结果输出

445、pandas.DataFrame.sub方法

445-1、语法

445-2、参数

445-3、功能

445-4、返回值

445-5、说明

445-6、用法

445-6-1、数据准备

445-6-2、代码示例

445-6-3、结果输出

二、推荐阅读

1、Python筑基之旅

2、Python函数之旅

3、Python算法之旅

4、Python魔法之旅

5、博客个人主页

一、用法精讲

441、pandas.DataFrame.mask方法
441-1、语法
# 441、pandas.DataFrame.mask方法
pandas.DataFrame.mask(cond, other=_NoDefault.no_default, *, inplace=False, axis=None, level=None)
Replace values where the condition is True.Parameters:
cond
bool Series/DataFrame, array-like, or callable
Where cond is False, keep the original value. Where True, replace with corresponding value from other. If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it).other
scalar, Series/DataFrame, or callable
Entries where cond is True are replaced with corresponding value from other. If other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame. The callable must not change input Series/DataFrame (though pandas doesn’t check it). If not specified, entries will be filled with the corresponding NULL value (np.nan for numpy dtypes, pd.NA for extension dtypes).inplace
bool, default False
Whether to perform the operation in place on the data.axis
int, default None
Alignment axis if needed. For Series this parameter is unused and defaults to 0.level
int, default None
Alignment level if needed.Returns:
Same type as caller or None if
inplace=True.
441-2、参数

441-2-1、cond(必须)一个条件,可以是布尔DataFrame、Series或数组,当满足此条件时,将替换值。

441-2-2、other(可选)替换的值,可以是标量、DataFrame、Series或数组,默认为_NoDefault.no_default,实际使用时通常会指定某个值。

441-2-3、inplace(可选,默认值为False)布尔值,是否直接修改原DataFrame。

441-2-4、axis(可选,默认值为None)参数用于选择沿哪个轴应用条件,0或'index'表示沿行,1或'columns'表示沿列。

441-2-5、level(可选,默认值为None)多级索引的级别,仅在某些情况下适用。

441-3、功能

        用于根据给定条件替换值的方法,它与DataFrame.where功能相反:where在满足条件时保持原值,而mask在满足条件时会用其他值替换原值。

441-4、返回值

        返回一个新的DataFrame,除非inplace=True,此时将直接修改原DataFrame。

441-5、说明

        无

441-6、用法
441-6-1、数据准备
441-6-2、代码示例
# 441、pandas.DataFrame.mask方法
# 441-1、用标量替换值
import pandas as pd
# 创建一个DataFrame实例
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [10, 20, 30, 40]
})
# 使用mask方法,将大于2的值替换为 0
masked_df = df.mask(df > 2, other=0)
print(masked_df, end='\n\n')# 441-2、用另一个DataFrame替换值
import pandas as pd
# 创建一个DataFrame实例
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [10, 20, 30, 40]
})
# 创建另一个DataFrame
replacement_df = pd.DataFrame({'A': [100, 200, 300, 400],'B': [1000, 2000, 3000, 4000]
})
# 使用mask方法,将大于2的值替换为replacement_df中的对应值
masked_df = df.mask(df > 2, other=replacement_df)
print(masked_df, end='\n\n')# 441-3、原地修改DataFrame
import pandas as pd
# 创建一个DataFrame实例
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [10, 20, 30, 40]
})
# 原地修改DataFrame,将大于2的值替换为-1
df.mask(df > 2, other=-1, inplace=True)
print(df)
441-6-3、结果输出
# 441、pandas.DataFrame.mask方法
# 441-1、用标量替换值
#    A  B
# 0  1  0
# 1  2  0
# 2  0  0
# 3  0  0# 441-2、用另一个DataFrame替换值
#      A     B
# 0    1  1000
# 1    2  2000
# 2  300  3000
# 3  400  4000# 441-3、原地修改DataFrame
#    A  B
# 0  1 -1
# 1  2 -1
# 2 -1 -1
# 3 -1 -1
442、pandas.DataFrame.query方法
442-1、语法
# 442、pandas.DataFrame.query方法
pandas.DataFrame.query(expr, *, inplace=False, **kwargs)
Query the columns of a DataFrame with a boolean expression.Parameters:
exprstr
The query string to evaluate.You can refer to variables in the environment by prefixing them with an ‘@’ character like @a + b.You can refer to column names that are not valid Python variable names by surrounding them in backticks. Thus, column names containing spaces or punctuations (besides underscores) or starting with digits must be surrounded by backticks. (For example, a column named “Area (cm^2)” would be referenced as `Area (cm^2)`). Column names which are Python keywords (like “list”, “for”, “import”, etc) cannot be used.For example, if one of your columns is called a a and you want to sum it with b, your query should be `a a` + b.inplacebool
Whether to modify the DataFrame rather than creating a new one.**kwargs
See the documentation for eval() for complete details on the keyword arguments accepted by DataFrame.query().Returns:
DataFrame or None
DataFrame resulting from the provided query expression or None if inplace=True.
442-2、参数

442-2-1、expr(必须)一个字符串,表示查询的表达式,表达式中的变量名应与DataFrame中的列名一致,可以使用任何有效的Python表达式语法。

442-2-2、inplace(可选,默认值为False)布尔值,如果为True,则在原地修改DataFrame,否则返回一个新的DataFrame。

442-2-3、**kwargs(可选)其他关键字参数,包括影响表达式执行环境的参数:

  • level:整数或级别名称,默认为None,查询沿着指定的级别进行计算(仅适用于多等级索引)。
  • global_dict:映射,将被用作全局命名空间中的变量。
  • local_dict:映射,将被用作局部命名空间中的变量。
442-3、功能

        通过查询表达式来过滤数据,从DataFrame中筛选出符合条件的行,它提供了一种更直观的方法,特别是对于较复杂的条件筛选,与标准的布尔索引方式相比,它显得更加简洁和可读。

442-4、返回值

        返回一个新的DataFrame,其中包含所有符合查询表达式条件的行,如果inplace=True,则直接修改原DataFrame并返回None。

442-5、说明

        无

442-6、用法
442-6-1、数据准备
442-6-2、代码示例
# 442、pandas.DataFrame.query方法
# 442-1、基本使用
import pandas as pd
# 创建一个DataFrame实例
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [10, 20, 30, 40],'C': ['foo', 'bar', 'foo', 'bar']
})
# 使用query方法筛选出'A'大于2的行
filtered_df = df.query('A > 2')
print(filtered_df, end='\n\n')# 442-2、结合多个条件
import pandas as pd
# 创建一个DataFrame实例
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [10, 20, 30, 40],'C': ['foo', 'bar', 'foo', 'bar']
})
# 使用query方法筛选出'A'大于2且'C'等于'foo'的行
filtered_df = df.query('A > 2 and C == "foo"')
print(filtered_df, end='\n\n')# 442-3、使用inplace=True
import pandas as pd
# 创建一个DataFrame实例
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [10, 20, 30, 40],'C': ['foo', 'bar', 'foo', 'bar']
})
# 使用query方法原地筛选出'A'大于2的行
df.query('A > 2', inplace=True)
print(df, end='\n\n')# 442-4、使用局部和全局命名空间中的变量
import pandas as pd
# 创建一个DataFrame实例
df = pd.DataFrame({'A': [1, 2, 3, 4],'B': [10, 20, 30, 40]
})
# 定义一些全局变量
low = 2
high = 30
# 使用query方法,引用全局变量进行筛选
filtered_df = df.query('A > @low and B < @high')
print(filtered_df)
442-6-3、结果输出
# 442、pandas.DataFrame.query方法
# 442-1、基本使用
#    A   B    C
# 2  3  30  foo
# 3  4  40  bar# 442-2、结合多个条件
#    A   B    C
# 2  3  30  foo# 442-3、使用inplace=True
#    A   B    C
# 2  3  30  foo
# 3  4  40  bar# 442-4、使用局部和全局命名空间中的变量
# Empty DataFrame
# Columns: [A, B]
# Index: []
443、pandas.DataFrame.__add__魔法方法
443-1、语法
# 443、pandas.DataFrame.__add__魔法方法
pandas.DataFrame.__add__(other)
Get Addition of DataFrame and other, column-wise.Equivalent to DataFrame.add(other).Parameters:
other
scalar, sequence, Series, dict or DataFrame
Object to be added to the DataFrame.Returns:
DataFrame
The result of adding other to DataFrame.
443-2、参数

443-2-1、other(必须)要与当前DataFrame相加的对象,可以是以下几种类型:

  • DataFrame:如果传入另一个DataFrame,则进行元素对元素的加法操作。
  • Series:如果传入Series,pandas会尝试将其广播到每一行或每一列,然后执行加法。
  • 标量值:如果传入一个标量值,则将该值加到DataFrame的每个元素上。
443-3、功能

        执行元素级的加法运算,对于两个DataFrame,它会对齐索引和列,然后逐元素相加,如果在某些位置上有缺失数据(NaN),结果将在这些位置保留NaN。

443-4、返回值

        返回一个新的DataFrame,其每个元素是当前DataFrame与other中对应元素相加的结果。

443-5、说明

        无

443-6、用法
443-6-1、数据准备
443-6-2、代码示例
# 443、pandas.DataFrame.__add__魔法方法
# 443-1、两个DataFrame相加
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
df2 = pd.DataFrame({'A': [10, 20, 30],'B': [40, 50, 60]
})
result = df1 + df2
print(result, end='\n\n')# 443-2、DataFrame与Series相加
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
s = pd.Series([10, 20], index=['A', 'B'])
result = df + s
print(result, end='\n\n')# 443-3、DataFrame与标量值相加
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
result = df + 10
print(result)
443-6-3、结果输出
# 443、pandas.DataFrame.__add__魔法方法
# 443-1、两个DataFrame相加
#     A   B
# 0  11  44
# 1  22  55
# 2  33  66# 443-2、DataFrame与Series相加
#     A   B
# 0  11  24
# 1  12  25
# 2  13  26# 443-3、DataFrame与标量值相加
#     A   B
# 0  11  14
# 1  12  15
# 2  13  16
444、pandas.DataFrame.add方法
444-1、语法
# 444、pandas.DataFrame.add方法
pandas.DataFrame.add(other, axis='columns', level=None, fill_value=None)
Get Addition of dataframe and other, element-wise (binary operator add).Equivalent to dataframe + other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, radd.Among flexible wrappers (add, sub, mul, div, floordiv, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.Parameters:
other
scalar, sequence, Series, dict or DataFrame
Any single or multiple element data structure, or list-like object.axis
{0 or ‘index’, 1 or ‘columns’}
Whether to compare by the index (0 or ‘index’) or columns. (1 or ‘columns’). For Series input, axis to match Series index on.level
int or label
Broadcast across a level, matching Index values on the passed MultiIndex level.fill_value
float or None, default None
Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.Returns:
DataFrame
Result of the arithmetic operation.
444-2、参数

444-2-1、other(必须)要与当前DataFrame相加的对象,可以是DataFrame、Series或标量值。

444-2-2、axis(可选,默认值为'columns'){0 or ‘index’, 1 or ‘columns’}, 如果other是一个Series,则该参数指示沿哪个轴对齐。

  • 0或'index':沿行对齐
  • 1或'columns':沿列对齐

444-2-3、level(可选,默认值为None)如果具有多层索引(MultiIndex),则此参数用来指定在哪一层上对齐;默认情况下,不使用多层索引。

444-2-4、fill_value(可选,默认值为None)在执行加法操作时,用于替代缺失数据(NaN)的值,如果一方的元素是NaN,则使用fill_value替代。

444-3、功能

        用于执行元素级的加法操作,同时提供了灵活的参数来处理不同类型的数据对齐和缺失数据填充。

444-4、返回值

        返回一个新的DataFrame,其每个元素是当前DataFrame与other中对应元素相加的结果,应用了指定的对齐和填充规则。

444-5、说明

        无

444-6、用法
444-6-1、数据准备
444-6-2、代码示例
# 444、pandas.DataFrame.add方法
# 444-1、两个DataFrame相加
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
df2 = pd.DataFrame({'A': [10, 20, 30],'B': [40, 50, 60]
})
result = df1.add(df2)
print(result, end='\n\n')# 444-2、DataFrame与Series相加(沿列对齐)
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
s = pd.Series([10, 20], index=['A', 'B'])
result = df.add(s, axis='columns')
print(result, end='\n\n')# 444-3、DataFrame与标量值相加
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
result = df.add(10)
print(result, end='\n\n')# 444-4、使用fill_value
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, None],'B': [4, None, 6]
})
df2 = pd.DataFrame({'A': [10, 20, 30],'B': [40, 50, 60]
})
result = df1.add(df2, fill_value=0)
print(result)
444-6-3、结果输出
# 444、pandas.DataFrame.add方法
# 444-1、两个DataFrame相加
#     A   B
# 0  11  44
# 1  22  55
# 2  33  66# 444-2、DataFrame与Series相加(沿列对齐)
#     A   B
# 0  11  24
# 1  12  25
# 2  13  26# 444-3、DataFrame与标量值相加
#     A   B
# 0  11  14
# 1  12  15
# 2  13  16# 444-4、使用fill_value
#       A     B
# 0  11.0  44.0
# 1  22.0  50.0
# 2  30.0  66.0
445、pandas.DataFrame.sub方法
445-1、语法
# 445、pandas.DataFrame.sub方法
pandas.DataFrame.sub(other, axis='columns', level=None, fill_value=None)
Get Subtraction of dataframe and other, element-wise (binary operator sub).Equivalent to dataframe - other, but with support to substitute a fill_value for missing data in one of the inputs. With reverse version, rsub.Among flexible wrappers (add, sub, mul, div, floordiv, mod, pow) to arithmetic operators: +, -, *, /, //, %, **.Parameters:
other
scalar, sequence, Series, dict or DataFrame
Any single or multiple element data structure, or list-like object.axis
{0 or ‘index’, 1 or ‘columns’}
Whether to compare by the index (0 or ‘index’) or columns. (1 or ‘columns’). For Series input, axis to match Series index on.level
int or label
Broadcast across a level, matching Index values on the passed MultiIndex level.fill_value
float or None, default None
Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.Returns:
DataFrame
Result of the arithmetic operation.
445-2、参数

445-2-1、other(必须)要与当前DataFrame相减的对象,可以是DataFrame、Series或标量值。

445-2-2、axis(可选,默认值为'columns'){0 or ‘index’, 1 or ‘columns’}, 如果other是一个Series,则该参数指示沿哪个轴对齐。

  • 0或'index':沿行对齐
  • 1或'columns':沿列对齐

445-2-3、level(可选,默认值为None)如果具有多层索引(MultiIndex),则此参数用来指定在哪一层上对齐;默认情况下,不使用多层索引。

445-2-4、fill_value(可选,默认值为None)在执行减法操作时,用于替代缺失数据(NaN)的值,如果一方的元素是NaN,则使用fill_value替代。

445-3、功能

        用于执行元素级的减法操作,同时提供了灵活的参数来处理不同类型的数据对齐和缺失数据填充。

445-4、返回值

        返回一个新的DataFrame,其每个元素是当前DataFrame与other中对应元素相减的结果,应用了指定的对齐和填充规则。

445-5、说明

        无

445-6、用法
445-6-1、数据准备
445-6-2、代码示例
# 445、pandas.DataFrame.sub方法
# 445-1、两个DataFrame相减
import pandas as pd
df1 = pd.DataFrame({'A': [10, 20, 30],'B': [40, 50, 60]
})
df2 = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
result = df1.sub(df2)
print(result, end='\n\n')# 445-2、DataFrame与Series相减(沿列对齐)
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
s = pd.Series([1, 2], index=['A', 'B'])
result = df.sub(s, axis='columns')
print(result, end='\n\n')# 445-3、DataFrame与标量值相减
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3],'B': [4, 5, 6]
})
result = df.sub(1)
print(result, end='\n\n')# 445-4、使用fill_value
import pandas as pd
df1 = pd.DataFrame({'A': [1, 2, None],'B': [4, None, 6]
})
df2 = pd.DataFrame({'A': [10, 20, 30],'B': [40, 50, 60]
})
result = df1.sub(df2, fill_value=0)
print(result)
445-6-3、结果输出
# 445、pandas.DataFrame.sub方法
# 445-1、两个DataFrame相减
#     A   B
# 0   9  36
# 1  18  45
# 2  27  54# 445-2、DataFrame与Series相减(沿列对齐)
#    A  B
# 0  0  2
# 1  1  3
# 2  2  4# 445-3、DataFrame与标量值相减
#    A  B
# 0  0  3
# 1  1  4
# 2  2  5# 445-4、使用fill_value
#       A     B
# 0  -9.0 -36.0
# 1 -18.0 -50.0
# 2 -30.0 -54.0

二、推荐阅读

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

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



http://www.chinasem.cn/article/1111290

相关文章

pandas中位数填充空值的实现示例

《pandas中位数填充空值的实现示例》中位数填充是一种简单而有效的方法,用于填充数据集中缺失的值,本文就来介绍一下pandas中位数填充空值的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是中位数填充?为什么选择中位数填充?示例数据结果分析完整代码总结在数据分析和机器学习过程中,处理缺失数

Pandas使用AdaBoost进行分类的实现

《Pandas使用AdaBoost进行分类的实现》Pandas和AdaBoost分类算法,可以高效地进行数据预处理和分类任务,本文主要介绍了Pandas使用AdaBoost进行分类的实现,具有一定的参... 目录什么是 AdaBoost?使用 AdaBoost 的步骤安装必要的库步骤一:数据准备步骤二:模型

Pandas统计每行数据中的空值的方法示例

《Pandas统计每行数据中的空值的方法示例》处理缺失数据(NaN值)是一个非常常见的问题,本文主要介绍了Pandas统计每行数据中的空值的方法示例,具有一定的参考价值,感兴趣的可以了解一下... 目录什么是空值?为什么要统计空值?准备工作创建示例数据统计每行空值数量进一步分析www.chinasem.cn处

使用Pandas进行均值填充的实现

《使用Pandas进行均值填充的实现》缺失数据(NaN值)是一个常见的问题,我们可以通过多种方法来处理缺失数据,其中一种常用的方法是均值填充,本文主要介绍了使用Pandas进行均值填充的实现,感兴趣的... 目录什么是均值填充?为什么选择均值填充?均值填充的步骤实际代码示例总结在数据分析和处理过程中,缺失数

如何使用 Python 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

利用Python调试串口的示例代码

《利用Python调试串口的示例代码》在嵌入式开发、物联网设备调试过程中,串口通信是最基础的调试手段本文将带你用Python+ttkbootstrap打造一款高颜值、多功能的串口调试助手,需要的可以了... 目录概述:为什么需要专业的串口调试工具项目架构设计1.1 技术栈选型1.2 关键类说明1.3 线程模

Python ZIP文件操作技巧详解

《PythonZIP文件操作技巧详解》在数据处理和系统开发中,ZIP文件操作是开发者必须掌握的核心技能,Python标准库提供的zipfile模块以简洁的API和跨平台特性,成为处理ZIP文件的首选... 目录一、ZIP文件操作基础三板斧1.1 创建压缩包1.2 解压操作1.3 文件遍历与信息获取二、进阶技

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中