53_Pandas中的条件替换值(where, mask)
我会解释如何在pandas中根据条件赋值。虽然它不使用 if 语句,但它可以处理条件分支,如 if then … 或 if then … else …。
具体值的替换见后面的文章,替换或删除缺失值NaN。
以下面的 pandas.DataFrame 为例。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'A': [-20, -10, 0, 10, 20],
'B': [1, 2, 3, 4, 5],
'C': ['a', 'b', 'b', 'b', 'a']})
print(df)
# A B C
# 0 -20 1 a
# 1 -10 2 b
# 2 0 3 b
# 3 10 4 b
# 4 20 5 a
以下内容进行说明。
- 带有 loc、iloc 的布尔索引引用
- pandas.DataFrame, Series 的 where() 方法
- False元素可以改变,True元素保持不变
- pandas.DataFrame, Series 的 mask() 方法
- True元素可以改变,False元素不变
- NumPy where() 函数
- True 和 False 元素都可以更改
带有 loc、iloc 的布尔索引引用
可以通过如下编写来根据条件替换标量值。
df.loc[df['A'] < 0, 'A'] = -100
df.loc[~(df['A'] < 0), 'A'] = 100
print(df)
# A B C
# 0 -100 1 a
# 1 -100 2 b
# 2 100 3 b
# 3 100 4 b
# 4 100 5 a
如果对 pandas.DataFrame 或 pandas.DataFrame的列(= pandas.Series)进行比较操作,将得到一个 bool 类型的 pandas.DataFrame 或 pandas.Series。
一个例子是处理 pandas.DataFrame (= pandas.Series) 的列。 ~ 是否定运算符。
print(df['A'] < 0)
# 0 True
# 1 True
# 2 False
# 3 False
# 4 False
# Name: A, dtype: bool
print(~(df['A'] < 0))
# 0 False
# 1 False
# 2 True
# 3 True
# 4 True
# Name: A, dtype: bool
使用 bool 类型 pandas.Series 作为 loc 或 iloc 行规范将只选择 True 行。 loc由行名和列名指定,iloc由行号和列号指定。
print(df.loc[df['A'] < 0, 'A'])
# 0 -100
# 1 -100
# Name: A, dtype: int64
带有loc和iloc的引用不仅可以用来取值,还可以用来赋值。 bool type pandas.Series 为 True 的行(满足条件的行)和指定的列元素更改为右侧的标量值。
df.loc[df['A'] < 0, 'A'] = -10
print(df)
# A B C
# 0 -10 1 a
# 1 -10 2 b
# 2 100 3 b
# 3 100 4 b
# 4 100 5 a
也可以指定 pandas.Series、列表或数组而不是标量值。相应的行值被替换。
df.loc[~(df['A'] < 0), 'A'] = df['B']
print(df)
# A B C
# 0 -10 1 a
# 1 -10 2 b
# 2 3 3 b
# 3 4 4 b
# 4 5 5 a
到目前为止的示例中,我们已经为现有列的元素赋值,但是指定新的列名会添加一个新列,并允许我们为满足条件的行赋值。
df.loc[df['B'] % 2 ==

本文详细介绍了在Pandas中如何使用where、mask等方法进行条件性数据替换及赋值,包括针对DataFrame和Series的不同操作方式,展示了如何利用这些方法处理复杂的数据条件逻辑。
最低0.47元/天 解锁文章
1354

被折叠的 条评论
为什么被折叠?



