Pandas:返回一列值大于另一列值的数据框

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

Pandas: return dataframe where one column's values are greater than another

pythonpandasdataframe

提问by RDJ

Apologies if this is a duplicate but I can't seem to find a working example in the pandas docs, SO or google.

抱歉,如果这是重复的,但我似乎无法在 Pandas 文档、SO 或 google 中找到工作示例。

How do you return a dataframe where the values of one column are greater than the values of another?

你如何返回一个数据框,其中一列的值大于另一列的值?

Should be something like this: df['A'].where(df['A']>df['B'])

应该是这样的: df['A'].where(df['A']>df['B'])

But this returns only a vector. I need the full filtered dataframe.

但这仅返回一个向量。我需要完整的过滤数据框。

回答by piRSquared

Try using query

尝试使用 query

df.query('A > B')

consider df

考虑 df

np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(10, 2), columns=list('AB'))
df

enter image description here

在此处输入图片说明

option 1

选项1

df.query('A > B')

option 2

选项 2

df[df.A.gt(df.B)]

enter image description here

在此处输入图片说明

回答by szeitlin

To do df['A'].where(df['A']>df['B'])in pandas syntax is essentially a mask. Instead of whereyou are taking a subset of the dataframe:

要做到df['A'].where(df['A']>df['B'])在大Pandas语法本质上是一个面具。而不是where您采用数据帧的一个子集:

df[df['A'] > df['B']]

df[df['A'] > df['B']]

example

例子