我需要使用 python 将 1 列转换为 3 列。我的数据是数据框类型
My data is:
0 1321.1321
1 text1
2 321113
0 1426.2156
1 text2
2 145454
我想以下列格式接收它:
col1 col2 col3
1321.1321 text1 321113
1426.2156 text2 145454
我尝试使用 pivot、reshape,但没有一个能提供我需要的解决方案
My data is:
0 1321.1321
1 text1
2 321113
0 1426.2156
1 text2
2 145454
我想以下列格式接收它:
col1 col2 col3
1321.1321 text1 321113
1426.2156 text2 145454
col1 col2 col3
1321.1321
text1
321113
1426.2156
text2
145454
请您参考如下方法:
使用GroupBy.cumcount对于按索引值按计数器分组的 Series.unstack reshape :
g = df.groupby(level=0).cumcount()
df = df.set_index(g, append=True)['col'].unstack(0).add_prefix('col')
print (df)
col0 col1 col2
0 1321.1321 text1 321113
1 1426.2156 text2 145454
如果值经常重复使用@Chris A 解决方案:
df = pd.DataFrame(df.to_numpy().reshape(-1, 3), columns=['col1', 'col2', 'col3'])
print (df)
col1 col2 col3
0 1321.1321 text1 321113
1 1426.2156 text2 145454
