python - 将熊猫系列转换成一行
问题描述
我计算了一个 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?
解决方案
用于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()
推荐阅读
- javascript - 如果 HTMl 没有值,则无法读取文本字段值
- python - 如何生成一个随机的、10 个字符长的大写字母、小写字母、数字和一些符号的序列?
- javascript - 在生产构建中启用 Nuxt 源映射
- c++ - 如何让 VS2015 正确拒绝在类声明中使用类前缀?
- swift - iphone X 的 TraitCollectionDidChange 行为不同
- actions-on-google - 谷歌模拟器上的谷歌智能家居操作不起作用
- python - 替换csv文件python中的整列
- selectize.js - selectize.js 避免自动排序选项
- embedded-linux - Yocto 最小 eSDK - world-pkgdata
- microsoft-graph-api - 即使 $top=1,Microsoft Graph 也会显示 @nextlink?