pandas DataFrame在布尔掩码上设置值

Mic*_*l K 15 python pandas

我正在尝试在pandas DataFrame中设置许多不同的值,以达到相同的值.我以为我理解了pandas的布尔索引,但是我没有找到关于这个特定错误的任何资源.

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
Run Code Online (Sandbox Code Playgroud)

上面,我想用值替换True掩码中的所有条目30.

我可以做df.replace,但掩盖在这里感觉更有效和直观.有人可以解释错误,并提供设置所有值的有效方法吗?

EdC*_*ica 14

不能在混合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)
df

Out[59]:
    A   B
0   1   a
1  30  30
2   3  30
Run Code Online (Sandbox Code Playgroud)

注意:如果您inplace=Truewhere方法中执行上述操作将会失败,因此df.where(mask, other=30, inplace=True)会引发:

TypeError:无法对具有非np.nan值的混合类型执行inplace boolean设置

编辑

好吧,经过一点误会后你仍然可以使用wherey只是反转掩码:

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
Run Code Online (Sandbox Code Playgroud)