【问题标题】:Transpose DataFrame in Pandas while preserving Index column在保留索引列的同时在 Pandas 中转置 DataFrame
【发布时间】:2016-01-02 16:30:43
【问题描述】:

问题是,当我转置 DataFrame 时,转置后的 DataFrame 的标题变成索引数值,而不是“id”列中的值。示例见以下原始数据:

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

逻辑流程

首先,这有助于摆脱作为标题放置的数字索引: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

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

如何解决此问题,使列为 [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

【问题讨论】:

    标签: pandas indexing dataframe transpose


    【解决方案1】:

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

    DF['id2'] = DF.index
    

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-09-12
      • 2018-06-01
      • 1970-01-01
      • 2018-11-06
      • 2013-09-08
      • 1970-01-01
      • 2019-05-07
      • 2014-07-28
      • 2013-01-16
      相关资源
      最近更新 更多