如何在多级索引DataFrame中删除指定索引的单行或多行?
多级索引DataFrame的行删除操作
你有一个多级索引的DataFrame,结构如下:
columnA columnB name timestamp x x
目前已掌握删除指定二级索引单行的代码:
df.drop(my_timestamp, level=1, axis=0, inplace=True)
针对你提出的两个问题,解决方案如下:
1. 删除同时指定name和timestamp索引的单一行
直接传入由name和timestamp组成的元组作为drop方法的参数即可,无需指定level:
# 示例:删除name为"Alice"、timestamp为"2023-01-01"的行 df.drop(("Alice", pd.Timestamp("2023-01-01")), axis=0, inplace=True)
多级索引的每一行索引本身就是一个元组,直接匹配该元组就能精准定位目标行。
2. 删除指定一个name下对应多个timestamp的多行
有两种简洁的实现方式:
方法一:构造索引元组列表
target_name = "Bob" target_timestamps = [pd.Timestamp("2023-01-02"), pd.Timestamp("2023-01-03")] # 生成要删除的索引元组集合 drop_indices = [(target_name, ts) for ts in target_timestamps] df.drop(drop_indices, axis=0, inplace=True)
方法二:结合loc筛选后删除
target_name = "Bob" target_timestamps = [pd.Timestamp("2023-01-02"), pd.Timestamp("2023-01-03")] # 筛选出目标name下指定timestamps的索引并组合成元组 drop_indices = [(target_name, ts) for ts in df.loc[target_name].loc[target_timestamps].index] df.drop(drop_indices, axis=0, inplace=True)
两种方法都能高效完成删除操作,构造元组列表的方式更直接,适合提前明确要删除的timestamp的场景。
内容的提问来源于stack exchange,提问作者alexx0186
相关产品推荐
相关产品推荐

