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

qbb*_*bbq 4 python dataframe python-3.x pandas

我有以下示例表:

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

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

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

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

蟒蛇:3.6.8

熊猫:0.25.0

jez*_*ael 5

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
Run Code Online (Sandbox Code Playgroud)