我需要使用python将1列转换为3列。我的数据是数据帧类型
My data is:
0 1321.1321
1 text1
2 321113
0 1426.2156
1 text2
2 145454
Run Code Online (Sandbox Code Playgroud)
我想以以下格式接收它:
col1 col2 col3
1321.1321 text1 321113
1426.2156 text2 145454
Run Code Online (Sandbox Code Playgroud)
我尝试使用枢轴,重塑形状,但没有一个可以提供所需的解决方案
My data is:
0 1321.1321
1 text1
2 321113
0 1426.2156
1 text2
2 145454
Run Code Online (Sandbox Code Playgroud)
我想以以下格式接收它:
col1 col2 col3
1321.1321 text1 321113
1426.2156 text2 145454
col1 col2 col3
1321.1321
text1
321113
1426.2156
text2
145454
Run Code Online (Sandbox Code Playgroud)
使用GroupBy.cumcount由计数器通过索引值与组Series.unstack的重塑:
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
Run Code Online (Sandbox Code Playgroud)
如果值重复设置,请使用@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
Run Code Online (Sandbox Code Playgroud)