【问题标题】:How to delete substrings with specific characters in a pandas dataframe?如何删除熊猫数据框中具有特定字符的子字符串?
【发布时间】:2018-12-09 23:08:25
【问题描述】:

我有一个看起来像这样的 pandas 数据框:

COL

hi A/P_90890 how A/P_True A/P_/93290 are AP_wueiwo A/P_|iwoeu you A/P_?9028k ?
...
 Im  fine, what A/P_49 A/P_0.0309 about you?

预期的结果应该是:

COL

hi how are you?
...
Im fine, what about you?

如何有效地从列和完整的 pandas 数据框中删除所有具有 A/P_ 的字符串?

我试过这个正则表达式:

A/P_(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+

但是,我不知道是否有更简单或更强大的方法可以从我的数据框中删除所有这些子字符串。如何删除所有以A/P_开头的字符串?

更新

我试过了:

df_sess['COL'] = df_sess['COL'].str.replace(r'A/P(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '')

而且它有效,但是我想知道是否有更强大的方法来做到这一点。可能使用正则表达式。

【问题讨论】:

标签: python regex python-3.x pandas


【解决方案1】:

一种方法是使用\S* 匹配A/P_ 之后的所有非空格,并添加\s 以删除要删除的字符串后的空格,例如:

df_sess['COL'] = df_sess['col'].str.replace(r'A/P_\S*\s', '')

在您的输入中,似乎存在拼写错误(或者至少我认为是这样),因此使用此输入:

df_sess = pd.DataFrame({'col':['hi A/P_90890 how A/P_True A/P_/93290 are A/P_wueiwo A/P_|iwoeu you A/P_?9028k ?',
                              'Im fine, what A/P_49 A/P_0.0309 about you?']})
print (df_sess['col'].str.replace(r'A/P_\S*\s', ''))
0            hi how are you ?
1    Im fine, what about you?
Name: col, dtype: object

你得到了预期的输出

【讨论】:

  • 我仍然有大量的空格,知道如何将它们删除到一个空格中吗?
  • @anon 你可以在replace(r'A/P_\S*\s', '') 后面的.str.replace(r'\s+', ' ') 选择所有由1 个或多个空格('\s+)组成的序列并用一个空格替换。
【解决方案2】:

怎么样:

(df['COL'].replace('A[/P|P][^ ]+', '', regex=True)
          .replace('\s+',' ', regex=True))

完整示例:

import pandas as pd

df = pd.DataFrame({
    'COL': 
    ["hi A/P_90890 how A/P_True A/P_/93290 AP_wueiwo A/P_|iwoeu you A/P_?9028k ?",
    "Im  fine, what A/P_49 A/P_0.0309 about you?"]
})

df['COL'] = (df['COL'].replace('A[/P|P][^ ]+', '', regex=True)
                      .replace('\s+',' ', regex=True))

返回(哦,前面多了一个空格?):

                        COL
0              hi how you ?
1  Im fine, what about you?

【讨论】:

    【解决方案3】:

    由于 replace() 函数 (https://github.com/pandas-dev/pandas/issues/21159) 中的 pandas 0.23.0 错误,在尝试用正则表达式模式替换时会发生错误:

    df.COL.str.replace(regex_pat, '', regex=True)
    ...
    --->
    TypeError: Type aliases cannot be used with isinstance().
    

    我建议将pandas.Series.apply 函数与预编译的正则表达式模式一起使用:

    In [1170]: df4 = pd.DataFrame({'COL': ['hi A/P_90890 how A/P_True A/P_/93290 are AP_wueiwo A/P_|iwoeu you A/P_?9028k ?', 'Im  fine, what A/P_49 A/P_0.0309 about you?']})
    
    In [1171]: pat = re.compile(r'\s*A/?P_[^\s]*')
    
    In [1172]: df4['COL']= df4.COL.apply(lambda x: pat.sub('', x))
    
    In [1173]: df4
    Out[1173]: 
                             COL
    0           hi how are you ?
    1  Im  fine, what about you?
    

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2021-03-29
      • 2019-03-14
      • 2021-07-03
      • 2014-07-09
      • 2019-03-06
      • 2017-06-02
      • 2019-03-15
      相关资源
      最近更新 更多