python - MultiIndex 的滚动级别
问题描述
假设我有一个数据框,其中我的列是 MultiIndex
col = pd.MultiIndex.from_product(
[[1, 2], ['A', 'B'], ['First', 'Second']],
names=['Cat', 'Dog', 'Bird']
)
dat = np.arange(16).reshape(2, -1)
df = pd.DataFrame(dat, columns=col)
df
Cat 1 2
Dog A B A B
Bird First Second First Second First Second First Second
0 0 1 2 3 4 5 6 7
1 8 9 10 11 12 13 14 15
我想调整列,使Bird
级别在顶部,Cat
级别向下移动到中间,然后Dog
到底部。
尝试 1
Usingswaplevel
可以连续使用,但是在中间创建一个完整的数据框只是为了增加列感觉很笨拙。
df.swaplevel(0, 2, 1).swaplevel(1, 2, 1).sort_index(1)
Bird First Second
Cat 1 2 1 2
Dog A B A B A B A B
0 0 2 4 6 1 3 5 7
1 8 10 12 14 9 11 13 15
尝试 2
创建新的MultiIndex
应该是高效的,但不是那么直观,并且可能不必要地冗长。
def roll(x):
return x[-1:] + x[:-1]
df.set_axis(
pd.MultiIndex.from_tuples(
[roll(x) for x in df.columns.values],
names=roll(df.columns.names)
), axis=1, inplace=False).sort_index(1)
Bird First Second
Cat 1 2 1 2
Dog A B A B A B A B
0 0 2 4 6 1 3 5 7
1 8 10 12 14 9 11 13 15
问题
是否有一种简洁直观的方法可以做到这一点,而无需在中间创建中间数据框?
解决方案
这是你需要的先生吗?使用reorder_levels
:
df.reorder_levels(['Bird','Cat','Dog'],axis=1).sort_index(level=0,axis=1)
Out[396]:
Bird First Second
Cat 1 2 1 2
Dog A B A B A B A B
0 0 2 4 6 1 3 5 7
1 8 10 12 14 9 11 13 15
推荐阅读
- dialogflow-es - 在对话流中从 bot 发起消息
- php - 如何交换多维数组中的最大和最小数字?
- google-cloud-platform - 气流信号 SIGTERM ,使用 bigquery 运算符,但任务成功
- python - 优化算法以处理元组、集合和字典
- hyperledger-fabric - Hyperledger Fabric 中的通道创建失败(没有 Docker)
- c# - 401 未经授权的错误或在 SignalR for WinForms 中没有返回消息
- javascript - 有没有办法使用 jquery 将数据附加到本地 excel 文件中?
- javascript - NodeJS - 日志记录 - 日志记录中的请求或堆栈号
- office-js - 由于加载项错误,Excel 任务窗格未加载
- python - 如何在小写和大写字母合并的点拆分列表的值