我需要在多列过滤器上过滤数据框,尝试使用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
尝试过的迭代:在我最近的尝试中,我能够获得每年的周数,但是我希望每周都能获得乘积,se和,sq和。
预期结果:
{
"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不能合并为一个。
答案 0 :(得分:1)
尝试:
df.groupby(by="year").apply(lambda grp: grp.groupby(by="week")[["product","se","sqe"]].sum().to_dict("index")).to_dict()
输出:
{'2019':
{'37': {'product': 2, 'se': 2, 'sqe': 1},
'38': {'product': 1, 'se': 0, 'sqe': 1}},
'2020':
{'1': {'product': 1, 'se': 0, 'sqe': 0},
'2': {'product': 1, 'se': 0, 'sqe': 0}}}
答案 1 :(得分:0)
要使用我的解决方案,分组键必须是唯一的,因此从您的数据样本中我 必须删除最后一行,因为 year == 2019 和 week == 37 发生得较早。
要获得预期的结果,可以运行:
df.drop(columns='col1').set_index(['year', 'week']).groupby('year').apply(
lambda grp: grp.reset_index(level=0, drop=True).to_dict(orient='index')).to_dict()
对于您的数据样本(没有最后一行),我得到了:
{2019: {37: {'product': 1, 'se': 1, 'sqe': 0},
38: {'product': 1, 'se': 0, 'sqe': 1}},
2020: { 1: {'product': 1, 'se': 0, 'sqe': 0},
2: {'product': 1, 'se': 0, 'sqe': 0}}}
可以将此代码扩展到更多级别,但是必须指定 您想要的所有分组级别。