【发布时间】:2020-10-12 09:06:46
【问题描述】:
我需要在多个列过滤器上过滤数据框,尝试过 groupby,但觉得它仅限于 2 个级别。
df_dic = {'col1': [1, 2, 3, 2, 1], 'year': ['2019', '2019', '2020', '2020', '2019'], 'week': ['37', '38', '1', '2', '37'], 'product': [1, 1, 1, 1, 1], 'se': [1, 0, 0, 0, 1], 'sqe': [0, 1, 0, 0, 1]}
数据框:
col1 year week product se sqe
1 2019 37 1 1 0
2 2019 38 1 0 1
3 2020 1 1 0 0
2 2020 2 1 0 0
1 2019 37 1 1 1
尝试过的迭代:在我最近的尝试中,我能够获得每年的周数,但我希望每周获得 product sum、se sum、sqe sum。
预期结果:
{
"2019": {
"37":{
"Product": 2,
"SE": 2,
"SQE":1
},
"38":{
"Product": 1,
"SE": 0,
"SQE":1
},
},
"2020":
{
"1":{
"Product": 2,
"SE": 0,
"SQE":0
}
}
}
任何帮助将不胜感激。 顺便说一句:这些产品,se 和 sqe 不能合二为一..
【问题讨论】:
-
试过 sn-p : df.groupby(['year']).apply(lambda grp: grp.groupby('week')['year'].count().to_dict() ).to_dict()
标签: python pandas pandas-groupby