布尔值掩码上的pandas DataFrame设置值

布尔值掩码上的pandas DataFrame设置值,第1张

布尔值掩码上的pandas DataFrame设置

不幸的是,不能在混合dtypes上使用布尔型掩码,可以使用pandas

where
设置值:

In [59]:df = pd.Dataframe({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})mask = df.isin([1, 3, 12, 'a'])df = df.where(mask, other=30)dfOut[59]:    A   B0   1   a1  30  302   3  30

注意:如果您

inplace=True
使用该
where
方法,上述 *** 作将失败,因此
df.where(mask, other=30,inplace=True)
会引发:

TypeError:无法对具有非np.nan值的混合类型进行就地布尔设置

编辑

好的,经过一些误会,您仍然可以使用

where
y,只需反转遮罩即可:

In [2]:    df = pd.Dataframe({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})mask = df.isin([1, 3, 12, 'a'])df.where(~mask, other=30)Out[2]:    A   B0  30  301   2   b2  30   f


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5667470.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存