pandas: filter rows of DataFrame with operator chaining

前端 未结 14 2323
悲哀的现实
悲哀的现实 2020-11-22 16:46

Most operations in pandas can be accomplished with operator chaining (groupby, aggregate, apply, etc), but the only way I

14条回答
  •  情深已故
    2020-11-22 17:17

    If you set your columns to search as indexes, then you can use DataFrame.xs() to take a cross section. This is not as versatile as the query answers, but it might be useful in some situations.

    import pandas as pd
    import numpy as np
    
    np.random.seed([3,1415])
    df = pd.DataFrame(
        np.random.randint(3, size=(10, 5)),
        columns=list('ABCDE')
    )
    
    df
    # Out[55]: 
    #    A  B  C  D  E
    # 0  0  2  2  2  2
    # 1  1  1  2  0  2
    # 2  0  2  0  0  2
    # 3  0  2  2  0  1
    # 4  0  1  1  2  0
    # 5  0  0  0  1  2
    # 6  1  0  1  1  1
    # 7  0  0  2  0  2
    # 8  2  2  2  2  2
    # 9  1  2  0  2  1
    
    df.set_index(['A', 'D']).xs([0, 2]).reset_index()
    # Out[57]: 
    #    A  D  B  C  E
    # 0  0  2  2  2  2
    # 1  0  2  1  1  0
    

提交回复
热议问题