用于转置数据帧的Python脚本

用于转置数据帧的Python脚本,python,dataframe,transpose,Python,Dataframe,Transpose,我有一个数据框,如下所示: 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 我需要将其转换到另一个数据帧,如这里的数据帧: 时间 1/1/12 0:15 27.84 1/1/12 0:30 28.08 1/1/12 0:45 27.6 你知道我该怎么做吗 1/1/12 0:15 27.84 1/1/12 0:30 28

我有一个数据框,如下所示:

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
我需要将其转换到另一个数据帧,如这里的数据帧: 时间

1/1/12 0:15 27.84
1/1/12 0:30 28.08
1/1/12 0:45 27.6
你知道我该怎么做吗

1/1/12 0:15 27.84
1/1/12 0:30 28.08
1/1/12 0:45 27.6
import numpy as np
a = np.array([[1, 2], [3, 4]])
a
array([[1, 2],
       [3, 4]])
a.transpose()
array([[1, 3],
       [2, 4]])

通过这种方式,如果您的df看起来像这样,您可以在python中使用数组中的numpy进行转置(如果df.set_index(“time”)有一个单独的时间列)

1/1/12 0:15 27.84
1/1/12 0:30 28.08
1/1/12 0:45 27.6
你可以简单地:

1/1/12 0:15 27.84
1/1/12 0:30 28.08
1/1/12 0:45 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
其中:

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

正因为如此:

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']

你尝试过搜索任何方法吗?如果有一种叫做
transpose()
的方法就好了……是的,有很多想法。看看这些列(df.columns),它们变成了您使用的序列,第一行值变成了另一个序列,最后索引或时间以下的值变成了新索引。把拼图拼在一起,你就到了。