Dynamically filtering a pandas dataframe

前端 未结 4 1721
渐次进展
渐次进展 2020-11-30 04:33

I am trying to filter a pandas data frame using thresholds for three columns

import pandas as pd
df = pd.DataFrame({\"A\" : [6, 2, 10, -5, 3],
                       


        
4条回答
  •  时光取名叫无心
    2020-11-30 05:34

    How I do this without creating a string and df.query:

    limits_dic = {"A" : 0, "B" : 2, "C" : -1}
    cond = None
    
    # Build the conjunction one clause at a time 
    for key, val in limits_dic.items():
        if cond is None:
            cond = df[key] > val
        else:
            cond = cond & (df[key] > val)
    
    df.loc[cond]
    
        A  B  C
    0   2  5  2
    1  10  3  1
    2   3  6  2
    

    Note the hard coded (>, &) operators (since I wanted to follow your example exactly).

提交回复
热议问题