2 回答
TA贡献1872条经验 获得超3个赞
我想你需要通过汇总sum和mean,通过扁平化多指标列和重塑stack有unstack:
df1 = (df.groupby(['Type','Product','Month'])
.agg({'Requirement': 'sum','Inventory':'mean'})
.rename(columns={'Requirement':'Sum of Requirement',
'Inventory':'Average of Inventory'})
.stack()
.unstack(2)
.reset_index()
.rename(columns={'level_2':'Values'}))
print (df1)
Month Type Product Values 18M01 18M02
0 A ABC001 Sum of Requirement 1.0 3.0
1 A ABC001 Average of Inventory 3.0 3.0
2 A ABC002 Sum of Requirement 2.0 NaN
3 A ABC002 Average of Inventory 4.0 NaN
4 B ABC001 Sum of Requirement 4.0 NaN
5 B ABC001 Average of Inventory 3.0 NaN
6 B ABC002 Sum of Requirement NaN 11.0
7 B ABC002 Average of Inventory NaN 4.0
TA贡献1883条经验 获得超3个赞
pivot_table做事的一种方式——
df1 = df.pivot_table('Requirement', ['Type','Product'], 'Month', aggfunc='sum')
df1['Values'] = 'Sum of Requirement'
df2 = df.pivot_table('Inventory', ['Type','Product'], 'Month', aggfunc='mean')
df2['Values'] = 'Average of Inventory'
df1.append(df2)
输出
Month 18M01 18M02 Values
Type Product
A ABC001 1.0 3.0 Sum of Requirement
ABC002 2.0 NaN Sum of Requirement
B ABC001 4.0 NaN Sum of Requirement
ABC002 NaN 11.0 Sum of Requirement
A ABC001 3.0 3.0 Average of Inventory
ABC002 4.0 NaN Average of Inventory
B ABC001 3.0 NaN Average of Inventory
ABC002 NaN 4.0 Average of Inventory
你可以扔进reset_index()去让它变得更好 -
df1.append(df2).reset_index()
Month Type Product 18M01 18M02 Values
0 A ABC001 1.0 3.0 Sum of Requirement
1 A ABC002 2.0 NaN Sum of Requirement
2 B ABC001 4.0 NaN Sum of Requirement
3 B ABC002 NaN 11.0 Sum of Requirement
4 A ABC001 3.0 3.0 Average of Inventory
5 A ABC002 4.0 NaN Average of Inventory
6 B ABC001 3.0 NaN Average of Inventory
7 B ABC002 NaN 4.0 Average of Inventory
添加回答
举报