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])
0

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.