循环以根据多个列条件筛选行

2024-06-06 13:49:58 发布

您现在位置: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

用于提取数据帧的代码,其中月份名称为所有年份的一月、二月等。例如

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

Tags: and数据indfsoonoutyear
1条回答
网友
1楼 · 发布于 2024-06-06 13:49:58

我认为您可以创建数据帧字典:

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

如果要按数据帧字典循环:

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

相关问题 更多 >