Pandas- 根据条件从 DataFrame 中选择行 [英] Pandas- Select rows from DataFrame based on condition
本文介绍了Pandas- 根据条件从 DataFrame 中选择行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
数据帧:
category value
A 25
B 10
A 15
B 28
A 18
需要选择满足以下条件的行,
1. category=A
和 10 到 20 之间的值
2. A以外的类别
Need to Select rows where following conditions are satisfied,
1. category=A
and value between 10 and 20
2. categories other than A
推荐答案
我认为你需要 布尔索引
:
I think you need boolean indexing
:
df1 = df[(df['category'] == 'A') & (df['value'].between(10,20))]
print (df1)
category value
2 A 15
4 A 18
然后:
df2 = df[(df['category'] != 'A') & (df['value'].between(10,20))]
print (df2)
category value
1 B 10
或者:
df3 = df[df['category'] != 'A']
print (df3)
category value
1 B 10
3 B 28
用 |
将两个条件加入 或
,不要忘记将 ()
添加到第一个条件.
Join both conditions with |
for or
, dont forget add ()
to first conditions.
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
这篇关于Pandas- 根据条件从 DataFrame 中选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文