简体   繁体   中英

How can I use a column data as values to create more headers

Sorry if my question sounds confusing, I can't find a way to word this better. I have this code here to calculate the pivot table

price_pivot_data = pd.pivot_table(out_data, values=["Price"], index=['Date', 'Payment method'])

And here's my current pivot table:

0                          Price
Date       Payment method       
2022-05-23 Void              0.0
2022-05-25 Credit            8.0
           Validation        8.0
2022-05-28 Credit            8.0

What I want is to use the Payment method column as headers for multiple column. So something like this:

Date        Void   Credit  Validation  Some other payment type 
2022-05-23  0.0    0.0     0.0         0.0
2022-05-25  0.0    8.0     8.0         0.0
2022-05-28  0.0    8.0     0.0         0.0

Regarding the other payment type column, NaN is fine. For the other payment type part, I can just manually add the column after so it's not required.

Is this possible? Thanks in advance.

You can try unstack then flatten the multi index column

df = price_pivot_data.unstack().fillna(0)
df.columns = df.columns.get_level_values(1)
print(df)

Payment method  Credit  Validation  Void
Date
2022-05-23         0.0         0.0   0.0
2022-05-25         8.0         8.0   0.0
2022-05-28         8.0         0.0   0.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM