Pandas:np.where 在数据帧上有多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27717111/
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-13 22:47:57  来源:igfitidea点击:

Pandas: np.where with multiple conditions on dataframes

pythonpandasmultiple-conditions

提问by swyx

hi folks i have look all over SO and google and cant find anything similar...

嗨,伙计们,我已经遍及 SO 和谷歌,但找不到任何类似的东西......

I have a dataframe x (essentially consisting of one row and 300 columns) and another dataframe y with same size but different data. I would like to modify x such that it is 0 if it has a different sign to y AND x itself is not 0, else leave it as it is. so this requires the use of np.where with multiple conditions. However the multiple condition examples i've seen all use scalars, and when i use the same syntax it does not seem to work (ends up setting -everything- to zero, no error). i'm worried about assign-by-reference issues hidden somewhere or other (y is x after shifting but as far as i can tell there is no upstream issue above this code) any ideas?

我有一个数据框 x(基本上由一行和 300 列组成)和另一个具有相同大小但数据不同的数据框 y。如果 x 与 y 有不同的符号并且 x 本身不为 0,我想修改 x 使其为 0,否则保持原样。所以这需要在多个条件下使用 np.where 。然而,我见过的多个条件示例都使用标量,当我使用相同的语法时,它似乎不起作用(最终将 - 一切 - 设置为零,没有错误)。我担心隐藏在某处或其他地方的按引用分配问题(移动后 y 是 x,但据我所知,此代码上方没有上游问题)有什么想法吗?

the code i am trying to debug is:

我试图调试的代码是:

tradesmade[i:i+1] = np.where((sign(x) != sign(y)) & (sign(x) != 0), 0, x) 

which just returns a bunch of zeros. I have also tried

它只返回一堆零。我也试过

tradesmade[i:i+1][(sign(x) != sign(y)) * (sign(x) != 0)] = 0

but this does not seem to work either. I have been at this for hours and am at a total loss. please help!

但这似乎也不起作用。我已经在这工作了几个小时,完全不知所措。请帮忙!

回答by gboffi

It is not clear to me what you exactlywant to do when a yelement is equal to zero... anyway the key point in this answer is "use np.logical_{and,not,or,xor}functions".

我不清楚当一个元素等于零时你到底想做什么y......无论如何,这个答案的关键点是“使用np.logical_{and,not,or,xor}函数”。

I thinkthat the following, albeit formulated differently from your example, does what you want, but if I'm wrong you should be able to combine different tests to achieve what you want,

认为以下虽然与您的示例不同,但可以满足您的需求,但是如果我错了,您应该能够结合不同的测试来实现您想要的,

x = np.where(np.logical_or(x*y>0, y==0), x, 0)

回答by aus_lacy

Similar to the post by @gboffi, but more centralized for your original request according to my understanding try:

类似于@gboffi 的帖子,但根据我的理解,对您的原始请求更加集中,请尝试:

x = np.where(np.logical_and((x*y) < 0, x != 0))

or

或者

x = np.where(((x*y) < 0) & (x != 0)))