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])
最佳答案
我认为你可以创建 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)
关于python - 循环根据多列条件过滤行 pandas python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60005576/