首页 > 解决方案 > 将熊猫系列转换成一行

问题描述

我计算了一个 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

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

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

标签: pythonpandasdataframe

解决方案


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

s = means.sort_index()
df = s.to_frame().T

或者:

df = pd.DataFrame([s.tolist()], columns=s.index)

但是,如果想要 DataFrame 的新行是可能的使用:

df.loc['avg'] = means

或者:

df.loc['avg'] = df.mean()

推荐阅读