重塑具有多个列但名称相同的数据框

问题描述 投票:0回答:1

您好,我有一个数据帧,其中有1个“唯一ID”作为索引,但对于同一unique_id,在同一行中有3个问题,但在同一行中有不同的数据。我研究了堆栈,融化,数据透视表。尝试使用

重塑下面的数据

“给定” enter image description here

最终产品:enter image description here

提供的代码结果:enter image description here

最近的代码输入:enter image description here

pandas csv stack pivot-table reshape
1个回答
0
投票
df = df.set_index(['Unique_ID'])
samples_per_id = len(df.columns) // 3
chunks = map(lambda k: df.iloc[:, k:k+3], range(0, samples_per_id, 3))
result = pd.concat(chunks, axis=0)

最后是result = result.sort_index()

© www.soinside.com 2019 - 2024. All rights reserved.