Pandas- Select rows from DataFrame based on condition

后端 未结 1 1095
刺人心
刺人心 2020-12-11 20:00

DataFrame:

category  value   
A         25  
B         10  
A         15  
B         28  
A                  


        
相关标签:
1条回答
  • 2020-12-11 20:45

    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
    
    0 讨论(0)
提交回复
热议问题