np.where在我的熊猫上不工作
问题内容:
我在使用Pandas时遇到np.where问题,这使我发疯,并且似乎无法通过Google,文档等解决。
我希望有人有见识。我确定它并不复杂。
我有一个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
这样就可以了。
但是这个:
Full_Names_Test_2['NewColumn'] = np.where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)
返回:
ValueError: either both or neither of x and y should be given
到底是怎么回事?
问题答案:
您需要传递布尔掩码和(两个)值列:
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)
参见np.where
文档。
或者可替换地使用的where
系列方法:
Full_Names_Test_2['MarketCap'].where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)