首页 > 解决方案 > 仅在熊猫数据框中查找和替换带有数字的字符串

问题描述

我正在尝试将包含数字的字符串替换为 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

标签: pythonpython-3.xstringpandasdataframe

解决方案


您可以通过pd.Series.str.containswith使用布尔索引loc

data.loc[data['A'].str.contains(r'\d'), 'A'] = ''

同样,使用maskor np.where

data['A'] = data['A'].mask(data['A'].str.contains(r'\d'), '')
data['A'] = np.where(data['A'].str.contains(r'\d'), '', data['A'])

推荐阅读