Pandas:保留多层索引中第二层索引重复项的首行
按多层索引的第二层ID去重并保留首行数据
需求说明
针对带有多层索引(date为第一层,ID为第二层)的DataFrame,当第二层索引ID存在重复项时,保留每个唯一ID对应的首次出现行,忽略第一层索引date的差异。
示例数据
你的示例数据结构如下:
| col_0 | col_1 | col_2 | col_3 | col_4 | |
|---|---|---|---|---|---|
| date | ID | ||||
| ('2022-01-01', 'identifier_0') | 26 | 46 | 44 | 21 | 10 |
| ('2022-01-01', 'identifier_1') | 25 | 45 | 83 | 23 | 45 |
| ('2022-01-01', 'identifier_2') | 42 | 79 | 55 | 5 | 78 |
| ('2022-01-01', 'identifier_3') | 32 | 4 | 57 | 19 | 61 |
| ('2022-01-01', 'identifier_4') | 30 | 25 | 5 | 93 | 72 |
| ('2022-01-02', 'identifier_0') | 42 | 14 | 56 | 43 | 42 |
| ('2022-01-02', 'identifier_1') | 90 | 27 | 46 | 58 | 5 |
| ('2022-01-02', 'identifier_2') | 33 | 39 | 53 | 94 | 86 |
| ('2022-01-02', 'identifier_3') | 32 | 65 | 98 | 81 | 64 |
| ('2022-01-02', 'identifier_4') | 48 | 31 | 25 | 58 | 15 |
| ('2022-01-03', 'identifier_0') | 5 | 80 | 33 | 96 | 80 |
| ('2022-01-03', 'identifier_1') | 15 | 86 | 45 | 39 | 62 |
| ('2022-01-03', 'identifier_2') | 98 | 3 | 42 | 50 | 83 |
解决方案
假设你的DataFrame变量名为df,多层索引的第二层名称为ID,直接使用drop_duplicates方法即可实现需求:
# 按ID去重,保留每个ID首次出现的行 df_unique = df.drop_duplicates(subset='ID', keep='first')
参数说明
subset='ID':指定以第二层索引ID作为重复判断的依据keep='first':保留每个重复ID对应的第一行,即该ID在数据中首次出现的记录(对应最早的date)
处理后结果
执行上述代码后,得到的df_unique将包含以下行(每个ID仅保留首次出现的记录):
| col_0 | col_1 | col_2 | col_3 | col_4 | |
|---|---|---|---|---|---|
| ('2022-01-01', 'identifier_0') | 26 | 46 | 44 | 21 | 10 |
| ('2022-01-01', 'identifier_1') | 25 | 45 | 83 | 23 | 45 |
| ('2022-01-01', 'identifier_2') | 42 | 79 | 55 | 5 | 78 |
| ('2022-01-01', 'identifier_3') | 32 | 4 | 57 | 19 | 61 |
| ('2022-01-01', 'identifier_4') | 30 | 25 | 5 | 93 | 72 |
内容的提问来源于stack exchange,提问作者Zen4ttitude
相关产品推荐
相关产品推荐

