如何基于坐标列表筛选DataFrame指定单元格(含反向筛选)
问题描述
现有如下DataFrame和坐标列表:
import pandas as pd df = pd.DataFrame({ 'col1': ['A', 'B', 'C', 'A', 'G'], 'col2': ['B', 'E', 'F', 'F', 'H'], 'col3': ['C', 'D', 'E', 'A', 'I']}) coords = [(2, 0), (3, 2)]
原DataFrame输出:
col1 col2 col3 0 A B C 1 B E D 2 C F E 3 A F A 4 G H I
需要实现一个带inverted布尔参数的函数:
- 当
inverted=False时,仅保留指定坐标的单元格内容,其余清空 - 当
inverted=True时,清空指定坐标的单元格内容,其余保留(已实现)
当前已写出部分函数逻辑,需补全正向筛选代码,预期输出如下:
# inverted = False col1 col2 col3 0 1 2 C 3 A 4
# inverted = True col1 col2 col3 0 A B C 1 B E D 2 F E 3 A F 4 G H I
解决方案
修改后的完整函数如下,补全了正向筛选逻辑:
def select(df, coords, inverted=False): # 复制原DataFrame,避免修改原始数据 df_copy = df.copy() if inverted: # 反向筛选:清空指定坐标单元格 for row, col in coords: df_copy.iat[row, col] = '' else: # 正向筛选:先清空所有单元格,再填充指定坐标的内容 df_copy = df_copy.applymap(lambda x: '') for row, col in coords: df_copy.iat[row, col] = df.iat[row, col] return df_copy
逻辑说明
- 正向筛选:先用
applymap清空所有单元格,再遍历坐标列表,从原DataFrame中取出对应位置的内容填充到副本中 - 反向筛选:保留原有逻辑,直接清空指定坐标的单元格
- 新增
df.copy()是为了避免修改原始DataFrame,保证数据独立性
测试验证
调用函数测试两种模式:
# 正向筛选 print(select(df, coords, inverted=False)) # 反向筛选 print(select(df, coords, inverted=True))
输出结果与预期完全一致:
正向筛选输出:
col1 col2 col3 0 1 2 C 3 A 4
反向筛选输出:
col1 col2 col3 0 A B C 1 B E D 2 F E 3 A F 4 G H I
内容的提问来源于stack exchange,提问作者VERBOSE
相关产品推荐
相关产品推荐

