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

提取所有年份月份名称为 Jan、Feb 等的数据帧的代码。例如。

 [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

我正在尝试为这个过程创建一个循环。

 [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

如果我打印它正在工作的数据框,但我想存储它们并稍后重用它们

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

1 回答 1

3

我认为您可以创建 DataFrames 字典:

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

你的解决方案应该改变:

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

然后可以选择每个月喜欢d['Jan']什么,工作什么的df1

如果想通过 DataFrames 字典循环:

for k, v in d.items():
    print (k)
    print (v)
于 2020-01-31T14:24:35.610 回答