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

如何将DataFrame列中的非空字符串替换为固定值

解决方法

不需要用正则表达式,直接通过布尔索引定位非空值赋值更简单高效:

import pandas as pd

data = {'item_name': ['apple', 'banana', 'cherry', 'pineapple', 'apple pie', 'banana split', 'hafts to chos', 'lov_frutz', 'I always pick apples', None, None, None]}
df = pd.DataFrame(data)

response = 'fruit'
# 定位非空行,替换为指定值
df.loc[pd.notna(df['item_name']), 'item_name'] = response

print(df)

运行后得到的结果完全符合预期:

item_name
0       fruit
1       fruit
2       fruit
3       fruit
4       fruit
5       fruit
6       fruit
7       fruit
8       fruit
9         NaN
10        NaN
11        NaN

你的正则方法失效原因

你写的r'\w\b'仅匹配单个单词字符加单词边界,只能替换字符串里的局部字符(比如每个单词的末尾字符),而非整个非空字符串。如果一定要用replace实现,可改用匹配任意非空字符串的正则:

df['item_name'] = df['item_name'].replace(to_replace=r'^.+$', value=response, regex=True)

但这种方式需要对每个字符串做正则匹配,效率不如布尔索引的方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:10:55