如何删除熊猫数据框中具有特定字符的子字符串?

时间:2018-07-01 14:07:50

标签: python regex python-3.x 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?

如何有效地从一列中删除所有具有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]))+', '')

它有效,但是我想知道是否有更健壮的方法来做到这一点。可能带有正则表达式。

3 个答案:

答案 0 :(得分: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?

答案 1 :(得分:2)

一种方法可能是使用\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

您将获得预期的输出

答案 2 :(得分:2)

由于df.COL.str.replace(regex_pat, '', regex=True) ... ---> TypeError: Type aliases cannot be used with isinstance(). 函数(https://github.com/pandas-dev/pandas/issues/21159)中的pandas 0.23.0错误,当尝试用正则表达式模式替换时,会发生错误:

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? 函数:

class Game():
    def __init__(self):
        self.player = Player("name")


    class Turn():
        def __init__(self):
            pass

        def end(self):
            #how update xp player

class Player():
    def __init__(self, name):
        self.name = name
        self.xp = 0
相关问题