看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)运营部把 8 月各渠道、各小时的 GMV 做成了 三级索引 DataFrame:
import pandas as pd, numpy as np
idx = pd.MultiIndex.from_product(
[['抖音', '快手', '微信'],
pd.date_range('2024-08-01', periods=3, freq='D'),
range(24)], # 小时
names=['渠道', '日期', '小时']
)
gmv = pd.Series(np.random.randint(1000, 5000, len(idx)),
index=idx,
name='GMV'
)
此时 gmv
的索引是 (渠道, 日期, 小时)
,直接打印层级太深。
用 一行 droplevel()
完成以下两步并打印结果:
代码如下:
# 1) 去掉“渠道”
by_date_hour = gmv.droplevel(0).reset_index()
print("层级 - 渠道 后:\n", by_date_hour.head())
# 2) 再去掉“小时”
by_date = gmv.droplevel(['渠道', '小时']) # 或 droplevel([0,2])
print("层级 - 渠道&小时 后:\n", by_date.head())
输出示例:
层级 - 渠道 后:
日期 小时 GMV
0 2024-08-01 0 3847
1 2024-08-01 1 2209
2 2024-08-01 2 3150
...
层级 - 渠道&小时 后:
2024-08-01 87456
2024-08-02 92341
2024-08-03 88712
Name: GMV, dtype: int64
通过 droplevel()
一键“拆楼”,多级索引秒变普通索引,报表立刻清爽。
(完)
更新时间:2025-08-22 08:16:35 标签:pandas python 索引层级