Python 如何在多索引 Pandas 数据框中选择大于某个值的单元格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32731498/
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
How to select cells greater than a value in a multi-index Pandas dataframe?
提问by Rex
Try 1:
尝试 1:
df[ df > 1.0 ]: this returned all cells in NAN.
df[ df > 1.0 ]:这返回了NAN.
Try2:
尝试2:
df.loc[ df > 1.0 ]: this returned KeyError: 0
df.loc[ df > 1.0 ]: 这回来了 KeyError: 0
df[df['A']> 1.0]: this works - But I want to apply the filter condition to all columns.
df[df['A']> 1.0]:这有效 - 但我想将过滤条件应用于所有列。
采纳答案by Anand S Kumar
If what you are trying to do is to select only rows where any one column meets the condition , you can use DataFrame.any()along with axis=1(to do row-wise grouping) . Example -
如果您想要做的是只选择任何一列满足条件的行,您可以使用DataFrame.any()with axis=1(to do-wise grouping) 。例子 -
In [3]: df
Out[3]:
A B C
0 1 2 3
1 3 4 5
2 3 1 4
In [6]: df[(df <= 2).any(axis=1)]
Out[6]:
A B C
0 1 2 3
2 3 1 4
Alternatively, if you are trying for filtering rows where all columns meet the condition , use .all()inplace of .any(). Example of all-
或者,如果您尝试过滤所有列都满足条件的行,请使用.all()代替.any()。示例all-
In [8]: df = pd.DataFrame([[1,2,3],[3,4,5],[3,1,4],[1,2,1]],columns=['A','B','C'])
In [9]: df
Out[9]:
A B C
0 1 2 3
1 3 4 5
2 3 1 4
3 1 2 1
In [11]: df[(df <= 2).all(axis=1)]
Out[11]:
A B C
3 1 2 1

