Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

python - Transposing group of data in pandas dataframe

I have a large dataframe like this:

|type| qt  | vol|
|----|---- | -- |
| A  | 1   | 10 |
| A  | 2   | 12 |
| A  | 1   | 12 |
| B  | 3   | 11 |
| B  | 4   | 20 |
| B  | 4   | 20 |
| C  | 4   | 20 |
| C  | 4   | 20 |
| C  | 4   | 20 |
| C  | 4   | 20 |

How can I transpose to the dataframe with grouping horizontally like that?

|A.            |B.            |C.            |
|--------------|--------------|--------------|
|type| qt | vol|type| qt | vol|type| qt | vol|
|----|----| ---|----|----| ---|----|----| ---|
| A  | 1  | 10 | B  | 3  | 11 | C  | 4  | 20 |
| A  | 2  | 12 | B  | 4  | 20 | C  | 4  | 20 |
| A  | 1  | 12 | B  | 4  | 20 | C  | 4  | 20 |
                              | C  | 4  | 20 |

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can group the dataframe on type then create key-value pairs of groups inside a dict comprehension, finally use concat along axis=1 and pass the optional keys parameter to get the final result:

d = {k:g.reset_index(drop=True) for k, g in df.groupby('type')}
pd.concat(d.values(), keys=d.keys(), axis=1)

Alternatively you can use groupby + cumcount to create a sequential counter per group, then create a multilevel index having two levels where the first level is counter and second level is column type itself, finally use stack followed by unstack to reshape:

c = df.groupby('type').cumcount()
df.set_index([c, df['type'].values]).stack().unstack([1, 2])

     A              B              C       
  type   qt  vol type   qt  vol type qt vol
0    A    1   10    B    3   11    C  4  20
1    A    2   12    B    4   20    C  4  20
2    A    1   12    B    4   20    C  4  20
3  NaN  NaN  NaN  NaN  NaN  NaN    C  4  20

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...