python - Pandas - 在重命名期间创建多索引列
问题描述
我试图找到一种简单的方法将平面列索引重命名为分层多索引列集。我遇到了一种方法,但它似乎有点笨拙 - 在 Pandas 中是否有更好的方法来做到这一点?
#!/usr/bin/env python
import pandas as pd
import numpy as np
flat_df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ACBD'))
print flat_df
# A C B D
# 0 27 67 35 36
# 1 80 42 93 20
# 2 64 9 18 83
# 3 85 69 60 84
nested_columns = {'A': ('One', 'a'),
'C': ('One', 'c'),
'B': ('Two', 'b'),
'D': ('Two', 'd'),
}
tuples = sorted(nested_columns.values(), key=lambda x: x[1]) # Sort by second value
nested_df = flat_df.sort_index(axis=1) # Sort dataframe by column name
nested_df.columns = pd.MultiIndex.from_tuples(tuples)
nested_df = nested_df.sort_index(level=0, axis=1) # Sort to group first level
print nested_df
# One Two
# a c b d
# 0 27 67 35 36
# 1 80 42 93 20
# 2 64 9 18 83
# 3 85 69 60 84
对分层列规范和数据框进行排序并假设它们会对齐似乎有点脆弱。同样排序三遍似乎很荒谬。我更喜欢的替代方案是nested_df = flat_df.rename(columns=nested_columns)
,但似乎rename
无法从平面列索引到多索引列。我错过了什么吗?
编辑:意识到如果按第二个值排序的元组与平面列名的排序不同,这将中断。绝对是错误的做法。
Edit2:回应@wen的回答:
nested_df = flat_df.rename(columns=nested_columns)
print nested_df
# (One, a) (One, c) (Two, b) (Two, d)
# 0 18 0 51 48
# 1 69 68 78 24
# 2 2 20 99 46
# 3 1 80 11 11
编辑3:
根据@ScottBoston 的回答,这是一个工作解决方案,它解释了嵌套列中未提及的扁平列:
#!/usr/bin/env python
import pandas as pd
import numpy as np
flat_df = pd.DataFrame(np.random.randint(0,100,size=(4, 5)), columns=list('ACBDE'))
print flat_df
# A C B D E
# 0 27 68 4 98 16
# 1 0 9 9 72 68
# 2 91 17 19 54 99
# 3 14 96 54 79 28
nested_columns = {'A': ('One', 'e'),
'C': ('One', 'h'),
'B': ('Two', 'f'),
'D': ('Two', 'g'),
}
nested_df = flat_df.rename(columns=nested_columns)
nested_df.columns = [c if isinstance(c, tuple) else ('', c) for c in nested_df.columns]
nested_df.columns = pd.MultiIndex.from_tuples(nested_df.columns)
print nested_df
# One Two
# e h f g E
# 0 27 68 4 98 16
# 1 0 9 9 72 68
# 2 91 17 19 54 99
# 3 14 96 54 79 28
解决方案
你可以试试:
df.columns = pd.MultiIndex.from_tuples(df.rename(columns = nested_columns).columns)
df
输出:
One Two
a c b d
0 27 67 35 36
1 80 42 93 20
2 64 9 18 83
3 85 69 60 84
推荐阅读
- c - 如何在结构中分配内存使其连续
- html - 同时在 HTML 和 CSS 规则中的 style 标签
- java - 休眠会话不更新实体
- node.js - heroku 构建失败。"mongoUrl"://"mongodb........" 语法错误等等
- asp.net-core - 即使在搭建所有身份页面后也找不到身份的 Layout.cshtml 文件
- javascript - Javascript 继承:原型链如何在原生原型之间工作
- python - 使用 Python 未收到 Gmail API 的完整正文消息
- node.js - 如何修复在 npm 中运行任何定义的脚本失败并出现错误 3221225781
- go - 如何在 Go 中逐行处理文件?
- batch-file - 使用批处理脚本将文件放在以它们命名的新文件夹中,如何让它忽略下划线和句点之间的所有内容?