将 pandas 系列转换为行

s5s*_*s5s 9 python dataframe pandas

我计算了 DatFrame 的平均值,得到了一个如下所示的 Series 对象:

means.sort_index()
0000    0.000204
0100   -0.000083
0200   -0.000260
0300   -0.000667
0400   -0.000025
0500    0.000127
0600    0.000227
0700   -0.000197
0800   -0.000497
0900   -0.000321
1000   -0.000520
1100    0.000562
1200   -0.000107
1300    0.000202
1400   -0.000445
1500    0.000665
1600    0.000288
1700   -0.000183
1800    0.000157
1900    0.000145
2000   -0.000206
2100    0.000388
2200    0.000363
2300    0.000297
dtype: float64
Run Code Online (Sandbox Code Playgroud)

我想将其作为一行添加到 DataFrame 中,但为此,我需要对其进行转换,以便每个索引都是一列。也就是说,我得到一个单行 DataFrame,其中索引作为列。我已经完成了一个枢轴,得到了一个 24x24 矩阵,然后我可以df.ffill().bfill()获取第一行,但这有点脏。means.T也不行。

如何将以上内容转换为以索引为列的 ​​1 行 DataFrame?

jez*_*ael 17

用于Series.to_frame一列DataFrame,然后转置DataFrame.T

s = means.sort_index()
df = s.to_frame().T
Run Code Online (Sandbox Code Playgroud)

或者:

df = pd.DataFrame([s.tolist()], columns=s.index)
Run Code Online (Sandbox Code Playgroud)

但如果想要向 DataFrame 添加新行,可以使用:

df.loc['avg'] = means
Run Code Online (Sandbox Code Playgroud)

或者:

df.loc['avg'] = df.mean()
Run Code Online (Sandbox Code Playgroud)