Selecting with complex criteria from pandas.DataFrame

后端 未结 4 1016
孤街浪徒
孤街浪徒 2020-11-22 11:12

For example I have simple DF:

import pandas as pd
from random import randint

df = pd.DataFrame({\'A\': [randint(1, 9) for x in xrange(10)],
                         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 11:42

    Another solution is to use the query method:

    import pandas as pd
    
    from random import randint
    df = pd.DataFrame({'A': [randint(1, 9) for x in xrange(10)],
                       'B': [randint(1, 9) * 10 for x in xrange(10)],
                       'C': [randint(1, 9) * 100 for x in xrange(10)]})
    print df
    
       A   B    C
    0  7  20  300
    1  7  80  700
    2  4  90  100
    3  4  30  900
    4  7  80  200
    5  7  60  800
    6  3  80  900
    7  9  40  100
    8  6  40  100
    9  3  10  600
    
    print df.query('B > 50 and C != 900')
    
       A   B    C
    1  7  80  700
    2  4  90  100
    4  7  80  200
    5  7  60  800
    

    Now if you want to change the returned values in column A you can save their index:

    my_query_index = df.query('B > 50 & C != 900').index
    

    ....and use .iloc to change them i.e:

    df.iloc[my_query_index, 0] = 5000
    
    print df
    
          A   B    C
    0     7  20  300
    1  5000  80  700
    2  5000  90  100
    3     4  30  900
    4  5000  80  200
    5  5000  60  800
    6     3  80  900
    7     9  40  100
    8     6  40  100
    9     3  10  600
    

提交回复
热议问题