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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…