gpt4 book ai didi

python - 仅在 Pandas 数据框中用数字查找和替换字符串

转载 作者:太空宇宙 更新时间:2023-11-04 02:07:13 26 4
gpt4 key购买 nike

我正在尝试用 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 使用 bool 索引与 loc :

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

类似地,使用masknp.where :

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

关于python - 仅在 Pandas 数据框中用数字查找和替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54411896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com