给出两个布尔Pandas 序列,比如s
和t
,我们如何用t
中的值替换s
的子集?
示例:
>>> s = pd.Series([True, False, False, True, True, False])
>>> t = pd.Series([True, True, False])
>>> s
0 True
1 False
2 False
3 True
4 True
5 False
dtype: bool
>>> t
0 True
1 True
2 False
dtype: bool
将s
值中的False
替换为t
时的预期输出:
>>> s
0 True
1 True
2 True
3 True
4 True
5 False
dtype: bool
也就是说,s
中值为False
的索引,即[1, 2, 5]
值被替换为[True, True, False]
,即t
.
我try 使用布尔掩码替换以下值,但没有成功.
>>> s[~s] = t
>>> s
0 True
1 True
2 False
3 True
4 True
5 NaN
dtype: object
使用s.mask(~s, t)
将返回类似的结果.为什么我在索引5得到一个NaN,谁不起作用?
虽然使用iloc Select 子集,然后替换Works,但这似乎是一种迂回的方法来实现这一点,我希望有一种更干净的方法来实现这一点.有吗?
>>> s.iloc[s[~s].index] = t
>>> s
0 True
1 True
2 True
3 True
4 True
5 False
dtype: bool