from pprint import pprint
import pandas as pd
input = [
{"item": "i1", "balance": 11, "warehouse": "W1"},
{"item": "i1", "balance": 12, "warehouse": "W4"},
{"item": "i1", "balance": 13, "warehouse": "W3"},
{"item": "i2", "balance": 11, "warehouse": "W2"},
{"item": "i2", "balance": 10, "warehouse": "W1"},
{"item": "i3", "balance": 10, "warehouse": "W3"},
]
df = pd.DataFrame(input)
df_pivot = df.pivot_table(
index=["item"], columns="warehouse", values="balance", fill_value=0
)
print(df_pivot)
output = df_pivot.reset_index().to_dict(orient="records")
pprint(output)
warehouse W1 W2 W3 W4
item
i1 11 0 13 12
i2 10 11 0 0
i3 0 0 10 0
[{'W1': 11, 'W2': 0, 'W3': 13, 'W4': 12, 'item': 'i1'},
{'W1': 10, 'W2': 11, 'W3': 0, 'W4': 0, 'item': 'i2'},
{'W1': 0, 'W2': 0, 'W3': 10, 'W4': 0, 'item': 'i3'}]
我想添加一个total列,其中是该行中for(w1,w2,..)的总和:
[
{'W1': 11, 'W2': 0, 'W3': 13, 'W4': 12, 'item': 'i1',total: 36},
{'W1': 10, 'W2': 11, 'W3': 0, 'W4': 0, 'item': 'i2',total: 21},
{'W1': 0, 'W2': 0, 'W3': 10, 'W4': 0, 'item': 'i3', total: 10}
]
2条答案
按热度按时间cbjzeqam1#
使用
pivot_table
和aggfunc='sum'
的margins
参数:输出:
bvn4nwqk2#
您可以在透视DataFrame上尝试列级别
sum
,