我刚刚发现了面具的这种奇怪行为,有人可以向我解释一下吗?
一种)
[输入]
df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
df['C'] ='hi'
df.mask(df[['A', 'B']]<3, inplace=True)
[输出]一种
乙
C
0
NaN
NaN
你好
1
NaN
3.0
你好
2
4.0
5.0
你好
3
6.0
7.0
你好
4
8.0
9.0
你好
乙)
[输入]
df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
df['C'] ='hi'
df.mask(df[['A', 'B']]<3)
[输出]一种
乙
C
0
NaN
NaN
NaN
1
NaN
3.0
NaN
2
4.0
5.0
NaN
3
6.0
7.0
NaN
4
8.0
9.0
NaN
先感谢您
最佳答案
不同结果的根本原因是您传递的 bool 数据帧与要屏蔽的数据帧的形状不同。 df.mask()
用值 inplace
填充缺失的部分.
从源码可以看到pandas.DataFrame.mask()调用 pandas.DataFrame.where()内部。 pandas.DataFrame.where()
然后调用 _where()替换条件为 False 的值的方法。
我就拿df.where()
例如,这里是示例代码:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(12).reshape(-1, 3), columns=['A', 'B', 'C'])
df1 = df.where(df[['A', 'B']]<3)
df.where(df[['A', 'B']]<3, inplace=True)
在本例中,df
是 A B C
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
df[['A', 'B']]<3
,cond
的值论证,是 A B
0 True True
1 False False
2 False False
3 False False
深挖_where()
方法,following lines是关键部分: def _where(...):
# align the cond to same shape as myself
cond = com.apply_if_callable(cond, self)
if isinstance(cond, NDFrame):
cond, _ = cond.align(self, join="right", broadcast_axis=1)
...
# make sure we are boolean
fill_value = bool(inplace)
cond = cond.fillna(fill_value)
自形cond
和 df
不一样,cond.align()
用 NaN
填补缺失值(value)。之后,cond
好像 A B C
0 True True NaN
1 False False NaN
2 False False NaN
3 False False NaN
然后用 cond.fillna(fill_value)
, NaN
值被替换为 inplace
的值.所以 C 列与 inplace
具有相同的值值(value)。尽管仍有一些代码( L9048 和 L9124-L9145 )与
inplace
相关.我们不需要关心细节,因为这些行的目的是替换条件为 False 的值。回想一下
df
是 A B C
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
df1=df.where(df[['A', 'B']]<3)
: cond
C 列是 False 因为默认值 inplace
是假的。做完后df.where()
, df
C列设置为other
的值参数是 NaN
默认情况下。 df.where(df[['A', 'B']]<3, inplace=True)
: cond
C 列是 True。做完后df.where()
, df
C列保持不变。 # print(df1)
A B C
0 0.0 1.0 NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
# print(df) after df.where(df[['A', 'B']]<3, inplace=True)
A B C
0 0.0 1.0 2
1 NaN NaN 5
2 NaN NaN 8
3 NaN NaN 11
关于python - 使用就地掩码的工作方式不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66473699/