Pandas- Select rows from DataFrame based on condition

久未见 提交于 2020-04-07 06:52:22

问题


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:


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

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.

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


来源:https://stackoverflow.com/questions/43632927/pandas-select-rows-from-dataframe-based-on-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!