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、博客个人主页
  • 14
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神奇夜光杯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值