在Pandas中转置DataFrame,同时保留Index列 [英] Transpose DataFrame in Pandas while preserving Index column

查看:3704
本文介绍了在Pandas中转置DataFrame,同时保留Index列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我想要转置的原始数据(但保持0,1,2,...索引完整并更改在最终转置的DataFrame中id到id2


我转置后的DataFrame,请注意标题是指数值而不是id值(这是我期待和需要的)



逻辑流程



首先,这有助于摆脱放置的数字索引作为标题:



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



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



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



这是我的代码:

  DF = pd.read_table(data,sep =\ t,index_col = [0])。transpose()#Add index_col = [0] to not not在转置期间将索引值作为自己的行
m,n = DF.shape
DF.reset_index(drop = False,inplace = True)
DF.head()

这无济于事:使用pandas将索引列添加到DataFrame

解决方案

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

  DF [ 'id2'] = DF.index 

现在,如果你想要 id 作为列标题然后你必须将其设置为索引,覆盖默认值:

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

我不知道重现您的数据,但这应该为您提供 id 的值。


The problem is, when I transpose the DataFrame, the header of the transposed DataFrame becomes the Index numerical values and not the values in the "id" column. See below original data for examples:

Original data that I wanted to transpose (but keep the 0,1,2,... Index intact and change "id" to "id2" in final transposed DataFrame).
DataFrame after I transpose, notice the headers are the Index values and NOT the "id" values (which is what I was expecting and needed)

Logic Flow

First this helped to get rid of the numerical index that got placed as the header: How to stop Pandas adding time to column title after transposing a datetime index?

Then this helped to get rid of the index numbers as the header, but now "id" and "index" got shuffled around: Reassigning index in pandas DataFrame & Reassigning index in pandas DataFrame

But now my id and index values got shuffled for some reason.

How can I fix this so the columns are [id2,600mpe, au565...]?

How can I do this more efficiently?

Here's my code:

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()

This didn't help much: Add indexed column to DataFrame with pandas

解决方案

If I understand your example, what seems to happen to you is that you transpose takes your actual index (the 0...n sequence as column headers. First, if you then want to preserve the numerical index, you can store that as id2.

DF['id2'] = DF.index

Now if you want id to be the column headers then you must set that as an index, overriding the default one:

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

I don't have your data reproduced, but this should give you the values of id across columns.

这篇关于在Pandas中转置DataFrame,同时保留Index列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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