np.where 在我的 Pandas 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33266344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:05:43  来源:igfitidea点击:

np.where Not Working in my Pandas

pythonpandaswhere

提问by Windstorm1981

I have an np.where problem using Pandas that is driving me crazy and I can't seem to solve through Google, the documentation, etc.

我在使用 Pandas 时遇到了 np.where 问题,这让我发疯了,我似乎无法通过 Google、文档等解决。

I'm hoping someone has insight. I'm sure it isn't complex.

我希望有人有洞察力。我相信它并不复杂。

I have a df where I'm checking the value in one column - and if that value is 'n/a' (as a string, not as in .isnull()), changing it to another value.

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

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

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

returns:

返回:

70      True
88     False
90      True
145     True
156     True
181     True
191     True
200     True
219     True
223    False
Name: MarketCap, dtype: bool

so that part works.

所以那部分工作。

but this:

但是这个:

Full_Names_Test_2['NewColumn'] = np.where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)

returns:

返回:

ValueError: either both or neither of x and y should be given

What is going on?

到底是怎么回事?

回答by Andy Hayden

You need to pass the boolean mask and the (two) values columns:

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

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)

See the np.wheredocs.

查看np.where文档。

or alternatively use the whereSeries method:

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

Full_Names_Test_2['MarketCap'].where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)