简体   繁体   中英

How to convert pandas dataframe using Unstack?

I want to convert the following DataFrame

数据框 1

into a new DataFrame

在此处输入图像描述

using pandas unstack function. Please help me out?

df = pd.DataFrame([["A", 1, 1, 10],
                   ["A", 2, 1, 20],
                   ["A", 1, 2, 30],
                   ["A", 2, 2, 40],
                   ["B", 1, 1, 50],
                   ["B", 2, 1, 60],
                   ["B", 1, 2, 70],
                   ["B", 2, 2, 80],
                   ["B", 1, 3, 90]], 
                  columns=["itemid", "segment", "pass", "p1"])

piv = df.pivot(["itemid", "segment"], "pass", "p1")
piv.columns = [f"p1_pass_{idx}" for idx in piv.columns]
piv.reset_index()

Output:

  itemid  segment  p1_pass_1  p1_pass_2  p1_pass_3
0      A        1       10.0       30.0        NaN
1      A        2       20.0       40.0        NaN
2      B        1       50.0       70.0       90.0
3      B        2       60.0       80.0        NaN

I don't know whether the use of unstack is totally necessary for you.

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