2

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])
noob
  • 3,601
  • 6
  • 27
  • 73

1 Answers1

3

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)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252