转置Pandas DataFrame并将列标题更改为列表 [英] Transpose Pandas DataFrame and change the column headers to a list

查看:600
本文介绍了转置Pandas DataFrame并将列标题更改为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Pandas子数据框

I have the following Pandas sub-dataframe

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

col1没有重复项.我想转置数据框并将列标题更改为col1值.理想情况下,输出应类似于

col1 has no duplicate. I want to transpose the dataframe and change the column header to col1 values. Ideally the output should look like

Variable  a     b
name1     10    72
name2     0.2  -0.1

很容易转换df并将第一列标记为Variable

it is easy to transpose the df and lable the first column as Variable

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

生成的DF将具有原始DF的索引作为列标题(并且它们没有排序并且不在我的数据中从1开始!)如何更改其余的列名?

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?

推荐答案

需要 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

如果需要索引中的列:

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

这篇关于转置Pandas DataFrame并将列标题更改为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆