在 Python Pandas 中,有没有办法让多行在一行中彼此相邻?维持秩序
In Python Pandas is there a way multiple rows next to each other on one row? keeping the order
current
name Mon Tues
sony 5 5
sony 4 6
coby 1 8
coby 2 7
Desired
name Mon Tues Mon Tues
sony 5 5 4 6
coby 1 8 2 7
我曾尝试使用 .melt,但它只是堆叠在顶部,所以它会在周一、周一、周二、周二使用,而不是周一、周二、周一、周二。
谢谢
这基本上是一列的数据透视表。您可以在枢轴之后对索引进行排序,在这种情况下,按 level=(1,0)
:
(df.assign(col=df.groupby('name').cumcount())
.pivot(index='name', columns='col').T
.sort_index(level=(1,0))
.reset_index(level=1,drop=True)
.T.reset_index()
)
输出:
name Mon Tues Mon Tues
0 coby 1 8 2 7
1 sony 5 5 4 6
current
name Mon Tues
sony 5 5
sony 4 6
coby 1 8
coby 2 7
Desired
name Mon Tues Mon Tues
sony 5 5 4 6
coby 1 8 2 7
我曾尝试使用 .melt,但它只是堆叠在顶部,所以它会在周一、周一、周二、周二使用,而不是周一、周二、周一、周二。
谢谢
这基本上是一列的数据透视表。您可以在枢轴之后对索引进行排序,在这种情况下,按 level=(1,0)
:
(df.assign(col=df.groupby('name').cumcount())
.pivot(index='name', columns='col').T
.sort_index(level=(1,0))
.reset_index(level=1,drop=True)
.T.reset_index()
)
输出:
name Mon Tues Mon Tues
0 coby 1 8 2 7
1 sony 5 5 4 6