2015-10-05 416 views
3

问题是,当我转置DataFrame时,转置的DataFrame的标题变为Index数值而不是“id”列中的值。看下面的原始数据的例子:在Pandas中转置DataFrame的同时保留索引列

原始数据,我想转置(但保留0,1,2,...索引完好,并在最终转置数据帧中将“id”更改为“id2”)
enter image description here 数据帧我转后,发现头是指数值,而不是“ID”的值(这是我期待和需要) enter image description here

逻辑流程

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

然后,这个帮助d摆脱了索引号为头的,但现在“id”和“指标”得到抛去: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

回答

3

如果我理解你的榜样,什么似乎发生在你的是,你transpose需要您的实际索引( 0 ... N序列列标题。首先,如果你再要保留数值指标,你可以存储为id2

DF['id2'] = DF.index 

现在如果你想id是列标题,那么你必须设置为指标,覆盖默认之一:

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

我没有你的数据复制,但是这应该给你的价值观跨列的id

相关问题