在保留索引列

时间:2015-10-05 21:43:11

标签: pandas indexing dataframe transpose

问题是,当我转置DataFrame时,转置的DataFrame的标题变为Index数值而不是“id”列中的值。有关示例,请参阅以下原始数据:

我希望转置的原始数据(但保持0,1,2,...索引完整并在最终转置的DataFrame中将“id”更改为“id2”)
enter image description here 转置后的 DataFrame,请注意标题是索引值而不是“id”值(这是我期待和需要的) enter image description here

逻辑流程

首先,这有助于摆脱作为标题放置的数字索引:How to stop Pandas adding time to column title after transposing a datetime index?

然后这有助于摆脱索引号作为标题,但现在“id”和“index”被改组:Reassigning index in pandas DataFrame& Reassigning index in pandas DataFrame

enter image description here

但是现在我的id和索引值由于某种原因被洗牌了。

如何解决此问题,以便列为[id2,600mpe,au565 ...]?

如何更有效地完成这项工作?

这是我的代码:

DF = pd.read_table(data,sep="\t",index_col = [0]).transpose() #Add index_col = [0] to not have index values as own row during transposition
m, n = DF.shape
DF.reset_index(drop=False, inplace=True)
DF.head()

这没有多大帮助:Add indexed column to DataFrame with pandas

1 个答案:

答案 0 :(得分:4)

如果我理解你的例子,你似乎发生的事情是你transpose获取你的实际索引(0 ... n序列作为列标题。首先,如果你想保留数字索引,您可以将其存储为id2

DF['id2'] = DF.index

现在,如果您希望id成为列标题,则必须将其设置为索引,覆盖默认值:

DF.set_index('id',inplace=True)
DF.T

我没有复制您的数据,但这应该为您提供跨列id的值。

相关问题