2 回答
TA贡献1890条经验 获得超9个赞
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
TA贡献1712条经验 获得超3个赞
您还可以将列转换Status为分类,并确保“待付款”是当前类别(即使它未在数据中表示)
df = pd.DataFrame({'Name': ['Bob', 'Bob', 'Susan', 'Susan', 'Jane','Jane'],
'Status': ['Paid', 'Paid', 'Paid OTP', 'Overdue', '', 'Upsell'],
'Amt': [100, 200, 300, 200, 0,60]})
df["Status"] = pd.Categorical(df["Status"])
if "To Be Paid" not in df["Status"].cat.categories:
df["Status"].cat.add_categories("To Be Paid", inplace=True)
df.pivot_table(values='Amt', index='Name', columns='Status', aggfunc=np.sum, fill_value=0, dropna=False)
Status 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
添加回答
举报