我有一个看起来像这样的 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_
的字符串以及完整的 pandas 数据框?
我试过这个正则表达式:
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]))+', '')
它确实有效,但是我想知道是否有更可靠的方法来做到这一点。可能使用正则表达式。
最佳答案
一种方法是使用 \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
你得到了预期的输出
关于python - 如何删除 Pandas 数据框中具有特定字符的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51124019/