我正在尝试将 pandas DataFrame 中的多个不同值全部设置为相同的值。我以为我了解 pandas 的 bool 索引,但我还没有找到关于这个特定错误的任何资源。
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})
mask = df.isin([1, 3, 12, 'a'])
df[mask] = 30
Traceback (most recent call last):
...
TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value
在上面,我想用值 30
替换掩码中的所有 True
条目。
我可以用 df.replace
来代替,但是这里的掩码感觉更高效、更直观。有人可以解释错误,并提供一种有效的方法来设置所有值吗?
最佳答案
不幸的是,你不能在混合数据类型上使用 bool 掩码,你可以使用 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)
df
Out[59]:
A B
0 1 a
1 30 30
2 3 30
注意:如果你在 where
方法中执行 inplace=True
上面的操作将会失败,所以 df.where(mask, other=30, inplace =True)
将引发:
TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value
编辑
好吧,经过一点点误解你仍然可以使用 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 B
0 30 30
1 2 b
2 30 f
关于python - pandas DataFrame 在 bool 掩码上设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30519140/