gpt4 book ai didi

python - 即使列中不存在数据,Pandas 也会使用自定义列进行数据透视

转载 作者:行者123 更新时间:2023-12-05 02:49:50 25 4
gpt4 key购买 nike

我有以下示例表:

df = pd.DataFrame({'Name': ['Bob', 'Bob', 'Susan', 'Susan', 'Jane','Jane'],
'Status': ['Paid', 'Paid', 'Paid OTP', 'Overdue', '', 'Upsell'],
'Amt': [100, 200, 300, 200, 0,60]})

我正在尝试使用以下代码创建数据透视表(有效):

table = pd.pivot_table(df, values='Amt', index=['Name'],columns=['Status'], aggfunc=np.sum, fill_value=0)

但是我需要包含一个持久列,例如:“To Be Paid”,无论表中是否有值。这样做的原因是,如果为该特定月份填写了“待支付”,则显示 0 值。

python :3.6.8

Pandas :0.25.0

最佳答案

使用Index.union如果 DataFrame.reindex 不存在,则为列名称添加新值:

cols = table.columns.union(['To Be Paid'], sort=False)
table = table.reindex(cols, axis=1, fill_value=0)
print (table)
Overdue Paid Paid OTP Upsell To Be Paid
Name
Bob 0 0 300 0 0 0
Jane 0 0 0 0 60 0
Susan 0 200 0 300 0 0

关于python - 即使列中不存在数据,Pandas 也会使用自定义列进行数据透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63896634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com