Pandas filter rows using multiple fields together

前端 未结 1 407
花落未央
花落未央 2020-12-21 16:38

I have a pandas DataFrame like this:

In [34]: people = pandas.DataFrame({\'name\' : [\'John\', \'John\', \'Mike\', \'Sarah\', \'Julie\'], \'age\         


        
相关标签:
1条回答
  • 2020-12-21 17:28

    This should work:

    people.set_index(people.columns.tolist(), drop=False).loc[filter].reset_index(drop=True)
    

    Cleaned up and with explanation

    # set_index with the columns you want to reference in tuples
    cols = ['name', 'age']
    people = people.set_index(cols, drop=False)
    #                                   ^
    #                                   |
    #   ensure the cols stay in dataframe
    
    #   does what you
    #   want but now has
    #   index that was
    #   not there
    # /--------------\
    people.loc[filter].reset_index(drop=True)
    #                 \---------------------/
    #                  Gets rid of that index
    
    0 讨论(0)
提交回复
热议问题