【问题标题】:finding and replacing strings with numbers only within a pandas dataframe仅在熊猫数据框中查找和替换带有数字的字符串
【发布时间】:2019-01-28 23:42:52
【问题描述】:

我正在尝试用 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

【问题讨论】:

    标签: python python-3.x string pandas dataframe


    【解决方案1】:

    您可以通过pd.Series.str.containsloc 使用布尔索引:

    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'])
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 2018-08-01
      • 2020-05-13
      • 2017-09-09
      • 2017-07-08
      • 1970-01-01
      • 2022-10-13
      • 2018-09-24
      相关资源
      最近更新 更多