pandas 添加了一个c列总计以按列名获取总计

olhwl3o2  于 2023-04-10  发布在  其他
关注(0)|答案(2)|浏览(154)
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}
  ]
cbjzeqam

cbjzeqam1#

使用pivot_tableaggfunc='sum'margins参数:

df_pivot = df.pivot_table(
    index=["item"], columns="warehouse", values="balance", fill_value=0,
    margins=True, margins_name='total', aggfunc='sum'
).drop('total')

output = df_pivot.reset_index().to_dict(orient="records")

输出:

[{'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}]
bvn4nwqk

bvn4nwqk2#

您可以在透视DataFrame上尝试列级别sum

pprint(
    df_pivot.assign(total=df_pivot.sum(axis=1)).reset_index().to_dict(orient='records')
)
[{'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}]

相关问题