我有以下示例表:
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)
但是,我需要包括一个持久性列,例如:无论表中是否有值,“待付款”。原因是如果在该特定月份填写了“待付款”,则显示0值。
的Python:3.6.8
熊猫: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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句