如何解决“ValueError:putmask:掩码和数据大小必须相同”

问题描述 投票:0回答:1

我有一个 pandas 数据框,我想使用

where()
方法替换其索引值,但出现以下错误。

ValueError: putmask: mask and data must be the same size

如何解决这个错误?

重现错误的步骤:

df = pd.DataFrame({'col': [1, 3, 5]})
df.index.where(lambda x: x>0, 10)      # ValueError: putmask: mask and data must be the same size

在上面的例子中,我希望用index=10替换index=0。

python pandas valueerror
1个回答
0
投票

Series.where
不同,
Index.where
不适用于可调用对象,因此使用
lambda
函数来屏蔽值不起作用。您必须传递一个与原始索引长度相同的布尔数组/系列/列表。

因此以下任何一项都有效。

df.index.where(df.index > 0, 10)           # <--- OK
df.index.where([False, True, True], 10)    # <--- OK

如果您传递一个长度不同的类似布尔数组,您将得到相同的错误:

df.index.where([True, True])               # <--- ValueError: putmask: mask and data must be the same size
df.index.where([True, True, True, False])  # <--- ValueError: putmask: mask and data must be the same size
© www.soinside.com 2019 - 2024. All rights reserved.