Pandas:np.where 在数据帧上有多个条件 [英] Pandas: np.where with multiple conditions on dataframes

查看:72
本文介绍了Pandas:np.where 在数据帧上有多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我在 SO 和 google 上都找遍了,找不到任何类似的东西......

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

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

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?

我试图调试的代码是:

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!

推荐答案

y 元素等于时,我不清楚你究竟想要做什么零...无论如何,这个答案的关键点是使用 np.logical_{and,not,or,xor} 函数".

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

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

I think that 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)

这篇关于Pandas:np.where 在数据帧上有多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆