You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何删除DataFrame含特殊字符的指定单元格值(不删整行整列)

清除DataFrame指定单元格内容的方案

实现思路

通过布尔索引精准定位目标单元格,直接赋值为空字符串或缺失值,仅清除目标内容,不影响其他行和列。

代码步骤

  1. 导入依赖库并创建DataFrame
import pandas as pd
import numpy as np

data = [['@Why', 1, 2], ['Stack', 1 ,'Example'], ['Overflow', 2, 'Anything'], ['row&', 3, 'Group' ]]
df = pd.DataFrame(data, columns=['A', 'B', 'C'])
  1. 清除目标单元格内容
    如果希望用空字符串填充:
df.loc[df['A'].isin(['@Why', 'row&']), 'A'] = ''

如果需要用缺失值标记:

df.loc[df['A'].isin(['@Why', 'row&']), 'A'] = np.nan

处理后结果

执行代码后,DataFrame将变为:

A  B         C
0          1         2
1     Stack  1   Example
2  Overflow  2  Anything
3          3      Group

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 17:40:30