Pandas- 根据条件从 DataFrame 中选择行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43632927/
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
Pandas- Select rows from DataFrame based on condition
提问by Ranjith
DataFrame:
数据帧:
category value
A 25
B 10
A 15
B 28
A 18
Need to Select rows where following conditions are satisfied,
1. category=A
and value between 10 and 20
2. categories other than A
需要选择满足以下条件的行,
1.category=A
值在 10 到 20 之间
2. A 以外的类别
回答by jezrael
I think you need boolean indexing
:
我认为你需要boolean indexing
:
df1 = df[(df['category'] == 'A') & (df['value'].between(10,20))]
print (df1)
category value
2 A 15
4 A 18
And then:
进而:
df2 = df[(df['category'] != 'A') & (df['value'].between(10,20))]
print (df2)
category value
1 B 10
Or:
或者:
df3 = df[df['category'] != 'A']
print (df3)
category value
1 B 10
3 B 28
EDIT: Join both conditions with |
for or
, dont forget add ()
to first conditions.
编辑:加入两个条件|
for or
,不要忘记添加()
到第一个条件。
df1 = df[((df['category'] == 'A') & (df['value'].between(10,20))) |
(df['category'] != 'A')]
print (df1)
category value
1 B 10
2 A 15
3 B 28
4 A 18