转置 Pandas DataFrame 并将列标题更改为列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47139203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Transpose Pandas DataFrame and change the column headers to a list
提问by Hamed
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. I want to transpose the dataframe and change the column header to col1
values. Ideally the output should look like
col1
没有重复。我想转置数据框并将列标题更改为col1
值。理想情况下,输出应如下所示
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 并将第一列标记为变量
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 开始!)如何更改其余的列名?
回答by jezrael
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