python - 循环根据多列条件过滤行 pandas python

标签 python pandas

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/

相关文章:

python - 如何识别谷歌应用引擎中引用属性损坏的对象

python - 获取嵌套列表字典中所有值的总和

python - SQLAlchemy: 'Table' 对象没有属性 'id'

python - 如何允许用户输入各种各样的内容并让它们在 numpy 数组中工作?

python - Groupby 大于 Pandas 非常慢

python - 使用 Pandas 计算滚动窗口中的不同字符串

Python 递归错误 : Simple operation crashes with Pandas. eval()

python - Open CV Hand Recognition - 让手掌的backProjection更准确?

python - Pandas 在两个系列之间进行元素比较的最佳方法

python-3.x - 当月份为小数位时,将 float 转换为日期时间(YYYY.MM float )