python-3.x - 使用列 MultiIndex 将 pandas 列拆分为两列
问题描述
我需要将DataFrame
列分成两列并向新列添加一个附加值。扭曲是我需要将原始列名提升一级并添加两个新列名。
给定一个DataFrame
h
:
>>> import pandas as pd
>>> h = pd.DataFrame({'a': [0.6, 0.4, 0.1], 'b': [0.2, 0.4, 0.7]})
>>> h
a b
0 0.6 0.2
1 0.4 0.4
2 0.1 0.7
我需要将原始列名提升一级并添加两个新列名。结果应如下所示:
>>> # some stuff...
a b
expected received expected received
0 0.6 1 0.2 1
1 0.4 1 0.4 1
2 0.1 1 0.7 1
我试过这个:
>>> h['a1'] = [1, 1, 1]
>>> h['b1'] = [1, 1, 1]
>>> t = [('f', 'expected'),('f', 'received'), ('g', 'expected'), ('g', 'received')]
>>> h.columns = pd.MultiIndex.from_tuples(t)
>>> h
f g
expected received expected received
0 0.6 0.2 1 1
1 0.4 0.4 1 1
2 0.1 0.7 1 1
这只是重命名列,但没有正确对齐它们。我认为问题在于a1
and列之间没有链接。b1
expected
received
如何将原始列名提升一级并添加两个新列名?
解决方案
我正在使用concat
with keys
,那么swaplevel
h1=h.copy()
h1[:]=1
pd.concat([h,h1],keys=['expected', 'received'],axis=1).\
swaplevel(0,1,axis=1).\
sort_index(level=0,axis=1)
Out[233]:
a b
expected received expected received
0 0.6 1.0 0.2 1.0
1 0.4 1.0 0.4 1.0
2 0.1 1.0 0.7 1.0
推荐阅读
- ios - Flutter firebase 分析应用程序在启动时崩溃
- qt - QMenu 中不显示 QAction 的图标
- java - 什么是引用 Java 外部类和内部类的 GC 根对象?
- c++ - 我的编译器未定义对 main 的引用出错
- javascript - 项目根目录下的 json.config 文件在哪里?
- python - Python 语言环境不适用于 alpine linux
- c++ - 借助 Windows API 启动 *.msi
- mysql - SQL Join 和条件
- javascript - 补间camera.position回到原来的位置three.js
- c# - 检查类中的任何属性是否为空