【问题标题】:Python script to transpose dataframe [closed]用于转置数据帧的 Python 脚本 [关闭]
【发布时间】:2017-08-11 18:46:15
【问题描述】:

我在这里显示了一个数据框:

time    0:15    0:30    0:45
1/1/12  27.84   28.08   27.6

我需要将它转置到另一个数据帧,比如这里的数据帧: 时间

1/1/12 0:15 27.84
1/1/12 0:30 28.08
1/1/12 0:45 27.6

知道我是如何进行的吗?

【问题讨论】:

  • 您是否尝试过搜索任何方法?
  • 如果有一些方法叫做transpose()...
  • 是的,有很多想法。查看列(df.columns),它们成为您使用的系列,第一行值成为另一个系列,最后低于时间的索引或值成为新索引。把拼图放在一起,你就在那里。

标签: python dataframe transpose


【解决方案1】:

如果你的 df 看起来像这样(df.set_index("time") 如果它有一个单独的时间列)。

df 

time    0:15    0:30    0:45        
1/1/12  27.84   28.08   27.6

你可以简单地:

# 1. Create a new DataFrame with two rows (columns and row1) - transpose them.
# 2. Set index to the old index to list and multiply by length of df2

df2 = pd.DataFrame([df.columns,df.iloc[0]]).T 
df2.index = df.index.tolist()*len(df2)
df2

这给出了:

        0       1
1/1/12  0:15    27.84
1/1/12  0:30    28.08
1/1/12  0:45    27.6

因为这个而起作用:

df.columns # Index(['0:15', '0:30', '0:45'], dtype='object')
df.iloc[0] # array([ 27.84,  28.08,  27.6 ])
df.index.tolist()*len(df.columns) # ['1/1/12', '1/1/12', '1/1/12']

【讨论】:

    【解决方案2】:
    import numpy as np
    a = np.array([[1, 2], [3, 4]])
    a
    array([[1, 2],
           [3, 4]])
    a.transpose()
    array([[1, 3],
           [2, 4]])
    

    通过这种方式,您可以在 python 中使用数组中的 numpy 进行转置

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-28
      • 2010-09-18
      • 2014-10-10
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多