python - 仅在熊猫数据框中查找和替换带有数字的字符串
问题描述
我正在尝试将包含数字的字符串替换为 pandas DataFrame 中的另一个字符串(在本例中为空字符串)。
我尝试使用 .replace 方法和正则表达式:
# creating dummy dataframe
data = pd.DataFrame({'A': ['test' for _ in range(5)]})
# the value that should get replaced with ''
data.iloc[0] = 'test5'
data.replace(regex=r'\d', value='', inplace=True)
print(data)
A
0 test
1 test
2 test
3 test
4 test
如您所见,它只替换字符串中的 '5' 而不是整个字符串。
我也尝试使用 .where 方法,但它似乎不适合我的需要,因为我不想替换任何不包含数字的字符串
这应该是这样的:
A
0
1 test
2 test
3 test
4 test
解决方案
您可以通过pd.Series.str.contains
with使用布尔索引loc
:
data.loc[data['A'].str.contains(r'\d'), 'A'] = ''
data['A'] = data['A'].mask(data['A'].str.contains(r'\d'), '')
data['A'] = np.where(data['A'].str.contains(r'\d'), '', data['A'])
推荐阅读
- mysql - Talend 7.1 与 MySQL Server 8.0 (localhost) 的连接失败
- sql - 在 Power BI 中映射数据库架构
- javascript - 在数字计数器上添加文本
- reactjs - 包装器 ReactJS
- javascript - 如何在 web3.eth.sendTransaction 中动态设置属性
- flutter - 当我试图在 android studio 中设置我的颤振环境时,它给了我很多错误那么现在该怎么办?
- node.js - 为 GO 执行的 vue 应用程序应用更改
- javascript - redux withrouter 不适用于反应。它将呈现新页面,但不会使用新状态/道具呈现
- swift - 使 AR 视频适应背景
- python - 使用 Python 加速并行读取大文件