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

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

问题描述

问题是,当我转置 DataFrame 时,转置后的 DataFrame 的标题变成了索引数值,而不是id"列中的值.有关示例,请参见以下原始数据:

我想转置的原始数据(但保持 0,1,2,... 索引不变,并在最终转置的 DataFrame 中将id"更改为id2").
转置后的数据帧,请注意标头是索引值而不是id"值(这是我期望和需要的)

逻辑流程

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

但是现在我的 id 和 index 值由于某种原因被打乱了.

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

我怎样才能更有效地做到这一点?

这是我的代码:

DF = pd.read_table(data,sep="	",index_col = [0]).transpose() #添加 index_col = [0] 以在转置期间不将索引值作为自己的行m, n = DF.shapeDF.reset_index(drop=False, inplace=True)DF.head()

这没有多大帮助:使用熊猫将索引列添加到 DataFrame

解决方案

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

DF['id2'] = DF.index

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

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

我没有复制您的数据,但这应该会为您提供跨列的 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="	",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,同时保留索引列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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