简体   繁体   中英

How can I run multiple filters in pandas?

I want to run multiple filters on different columns like 'Frequency', 'Decile' and 'Audience' as 'all' and 'Dimension' = 'campaign' and KPI name='honda_2018...' from an excel sheet imported in pandas. I am running the following code:

def filter_df(df, *args):
    for 'Frequency', 'All' in args:
        df = df[df['Frequency'] == 'All']
    return df

It is giving me an error SyntaxError: can't assign to literal . Please help

You can try .loc

Sample Data:

my_frame = pd.DataFrame(data={'name' : ['alex5','martha1','collin4','cynthia9'],
                              'simulation1':[71,4.8,65,4.7],
                              'simulation2':[71,4.8,69,4.7],
                              'simulation3':[70,3.8,68,4.9],
                              'experiment':[70.3,3.5,65,4.4]})
my_frame

Running this code below will return the index [1,2,3]:

my_frame.loc[(my_frame["simulation1"] == 4.8)]

Then if you want to filter more column use & , this code below will return index [2,3]:

my_frame.loc[(my_frame["simulation1"] == 4.8) &  \
             (my_frame["simulation2"] == 69)
            ]

Rinse and repeat until you're satisfied.

As I know it's possible

df = df[df['Frequency'] == 'All' and df['Something'] == 'Something else']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM