简体   繁体   中英

loop to filter rows based on multiple column conditions pandas python

df

month year  Jelly Candy Ice_cream.....and so on
JAN    2010  12    11    10
FEB    2010  13     1     2
MAR    2010  12     2     1 
....
DEC    2019  2      3     4

Code to extract dataframes where month names are Jan, Feb etc for all years. For eg.

 [IN]filterJan=df[df['month']=='JAN']
     filterJan
 [OUT] 
 month  year  Jelly Candy Ice_cream.....and so on
 JAN    2010  12    11    10
 JAN    2011  13     1     2
 ....
 JAN    2019  2      3     4

I am trying to make a loop for this process.

 [IN]for month in ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']:
         filter[month]=df[df['month']==month]
  [OUT]
  ----> 3     filter[month]=batch1_clean_Sales_database[batch1_clean_Sales_database['month']==month]

   TypeError: 'type' object does not support item assignment

If I print the dataframes it is working, but i want to store them and reuse them later

       [IN]for month in ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']:
                print(df[df['month']==month])

I think you can create dictionary of DataFrames:

d = dict(tuple(df.groupby('month')))

Your solution should be changed:

d = {}
for month in ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']:
    d[month] = df[df['month']==month]

Then is possible select each month like d['Jan'] , what working like df1 .

If want loop by dictionary of DataFrames:

for k, v in d.items():
    print (k)
    print (v)

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