我有一个像这样的数据表:
Run, test1, test2
1, 100, 102.
2, 110, 100.
3, 108, 105.
我希望将两列合并在一起,如下所示:
Run, results
1, 100
1, 102
2, 110
2, 100
3, 108
3, 105
如何在 Pandas 中做到这一点?非常感谢!
最佳答案
使用stack
使用 Multiindex
按 double reset_index
列:
df = df.set_index('Run').stack().reset_index(drop=True, level=1).reset_index(name='results')
print (df)
Run results
0 1 100.0
1 1 102.0
2 2 110.0
3 2 100.0
4 3 108.0
5 3 105.0
或者melt
:
df = df.melt('Run', value_name='results').drop('variable', axis=1).sort_values('Run')
print (df)
Run results
0 1 100.0
3 1 102.0
1 2 110.0
4 2 100.0
2 3 108.0
5 3 105.0
Numpy 解决方案 numpy.repeat
:
a = np.repeat(df['Run'].values, 2)
b = df[['test1','test2']].values.flatten()
df = pd.DataFrame({'Run':a , 'results': b}, columns=['Run','results'])
print (df)
Run results
0 1 100.0
1 1 102.0
2 2 110.0
3 2 100.0
4 3 108.0
5 3 105.0
关于Pandas Dataframe 合并 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46365490/