You need to enable JavaScript to run this app. 如何用Pandas将仅含单个指定字符的单元格替换为空?
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas将仅含单个指定字符的单元格替换为空?

解决方案

可以利用 pandas 的 replace 方法配合正则表达式,精准匹配**仅包含单个'-'**的单元格并替换为空字符串:

import pandas as pd

# 构建示例DataFrame
df1 = pd.DataFrame({'Number' : ['one-five', 'two', '-', '-', 'five'],
                    'Color' : ['-', 'red', 'blue-black','yellow', '-']})

# 替换仅含单个'-'的单元格
df1 = df1.replace('^-$', '', regex=True)
print(df1)

代码说明

  • ^-$ 是正则表达式,^ 匹配字符串开头,$ 匹配字符串结尾,合起来表示整个单元格内容就是单个'-'
  • regex=True 参数告诉 pandas 按照正则规则进行匹配替换
  • 执行后,像 'one-five'、'blue-black' 这类包含'-'但还有其他字符的单元格会被保留,只有纯'-'的单元格会被替换为空字符串

运行后得到的结果如下:

Number        Color
0  one-five             
1      two         red
2                 blue-black
3                 yellow
4     five             

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:15:44