Python 当列名在dataframe中通过数字重复时,如何将列转换为行?

Python 当列名在dataframe中通过数字重复时,如何将列转换为行?,python,pandas,Python,Pandas,我有一个像这样的dataframe列名 id salary year emp_type salary1 year1 emp_type1 salary2 year2 emp_type2 .. salary9 year9 emp_type9 1 xx xx xx .. .. 2 .. .. 3 我希望像这样将列旋转到行 id salary year emp_type ------------------

我有一个像这样的dataframe列名

id salary year emp_type salary1 year1 emp_type1 salary2 year2 emp_type2 .. salary9 year9 emp_type9
1   xx    xx   xx .. ..
2   ..    ..
3
我希望像这样将列旋转到行

id           salary            year                emp_type
-------------------------------------------------------------------
       value of salary     value of year     value of emp_type
       value of salary1    value of year1    value of emp_type1
             ..                  ..                .. 
             ..                  ..                ..
       value of salary9    value of year9    value of emp_type9

如果保证列按此顺序排列,您只需从重塑后的旧数据帧创建一个新数据帧:

new_df = pd.DataFrame(old_df.values.reshape((-1, 3)), 
                      columns=['salary', 'year', 'emp_type'])

不过,新的数据帧将不会保留旧的索引。

由@Marat给出的解决方案应该有效。在这里,我使用了9列,它是有效的

df = pd.DataFrame(['1000', 2011, 'Type1', '2000', 2012, 'Type2', '3000', 2013, 'Type3',
                   '4000', 2014, 'Type4', '5000', 2015, 'Type5', '6000', 2016, 'Type6',
                   '8000', 2018, 'Type7', '8000', 2018, 'Type8', '9000', 2019, 'Type9'])
df = pd.DataFrame(df.values.reshape(-1,3),columns=['salary', 'year', 'emp_type'])
print(df)
输出:

  salary  year emp_type
0   1000  2011    Type1
1   2000  2012    Type2
2   3000  2013    Type3
3   4000  2014    Type4
4   5000  2015    Type5
5   6000  2016    Type6
6   8000  2018    Type7
7   8000  2018    Type8
8   9000  2019    Type9

谢谢你的回答。但我不明白-1和3@devnext形状是(行、列、*任何其他维度)。将任何尺寸替换为-1意味着强制其他尺寸,然后计算此尺寸的大小。这里,重塑(-1,3)的意思是:重塑为三列,不管需要多少行,谢谢你们的回答。但不工作时显示此错误“无法将大小为176293的数组重塑为形状(3)”@devnext有一个额外的列。id是原始数据帧中的列还是索引?