简体   繁体   English

转置Pandas DataFrame并将列标题更改为列表

[英]Transpose Pandas DataFrame and change the column headers to a list

I have the following Pandas sub-dataframe 我有以下Pandas子数据帧

         col1  name1  name2
522      a     10     0.2
1021     b     72    -0.1

col1 has no duplicate. col1没有重复。 I want to transpose the dataframe and change the column header to col1 values. 我想转置数据帧并将列标题更改为col1值。 Ideally the output should look like 理想情况下,输出应该是这样的

Variable  a     b
name1     10    72
name2     0.2  -0.1

it is easy to transpose the df and lable the first column as Variable 很容易转换df并将第一列标记为Variable

df.transpose().reset_index().rename(columns={'index':'Variable'})

the resulted DF will have indices of original DF as column headers (and they are not sorted and dont start from 1 in my data!) How can I change the rest of column names? 结果DF将原始DF的索引作为列标题(并且它们没有排序,并且不从我的数据中的1开始!)如何更改列名的其余部分?

Need set_index + T : 需要set_index + T

df = df.set_index('col1').T
print (df)
col1      a     b
name1  10.0  72.0
name2   0.2  -0.1

df = df.set_index('col1').T.rename_axis('Variable').rename_axis(None, 1)
print (df)
             a     b
Variable            
name1     10.0  72.0
name2      0.2  -0.1

If need column from index: 如果需要来自索引的列:

df = df.set_index('col1').T.rename_axis('Variable').rename_axis(None, 1).reset_index()
print (df)
  Variable     a     b
0    name1  10.0  72.0
1    name2   0.2  -0.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM