np.where不能在我的熊猫中工作

Win*_*981 7 python where pandas

我有一个使用熊猫的np.where问题让我发疯,我似乎无法通过谷歌,文档等解决.

我希望有人有洞察力.我敢肯定它并不复杂.

我有一个df我正在检查一列中的值 - 如果该值是'n/a'(作为字符串,而不是.isnull()),将其更改为另一个值.

Full_Names_Test_2['MarketCap'] == 'n/a'

收益:

70      True
88     False
90      True
145     True
156     True
181     True
191     True
200     True
219     True
223    False
Name: MarketCap, dtype: bool
Run Code Online (Sandbox Code Playgroud)

这部分是有效的.

但是这个:

Full_Names_Test_2['NewColumn'] = np.where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)
Run Code Online (Sandbox Code Playgroud)

收益:

ValueError: either both or neither of x and y should be given
Run Code Online (Sandbox Code Playgroud)

到底是怎么回事?

And*_*den 10

您需要传递布尔掩码和(两个)值列:

np.where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)
# should be
np.where(Full_Names_Test_2['MarketCap'] == 'n/a', Full_Names_Test_2['MarketCap'], 7)
Run Code Online (Sandbox Code Playgroud)

查看np.where文档.

或者可替换地使用where系列方法:

Full_Names_Test_2['MarketCap'].where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)
Run Code Online (Sandbox Code Playgroud)

  • @Windstorm1981 fwiw,我认为有关此方法和此错误消息的文档可能会更清晰。需要第二个参数并不明显(足够了,IMO)。 (4认同)