且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-15 12:40:28

为此,您不能在混合dtypes上使用布尔掩码,可以使用pandas where设置值:

You can't use the boolean mask on mixed dtypes for this unfortunately, you can use pandas where to set the values:

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)将引发:

Note: that the above will fail if you do inplace=True in the where method, so df.where(mask, other=30, inplace=True) will raise:

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

TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value

编辑

好的,经过一些误会,您仍然可以使用where y只是将遮罩反转:

OK, after a little misunderstanding you can still use where y just inverting the mask:

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