python - 从列中删除带冒号的单词 - 为什么它不起作用?

标签 python regex string pandas

这是我的 pandas 数据框

Description                        ID       Date
wa119:d Here comes the first row   id_112   2018/03/02
ax21:3 Here comes the second row   id_115   2018/03/02
bC230:13 Here comes the third row  id_234   2018/03/02

数据类型是

print(df.dtypes)

Description             object
ID                      object
Date                    datetime64[ns]
dtype: object

我想删除那些包含冒号的单词。在本例中,这将是 wa119:d、ax21:3 和 bC230:13,因此我的新数据集应如下所示:

Description                ID      Date
Here comes the first row   id_112  2018/03/02
Here comes the second row  id_115  2018/03/02
Here comes the third row   id_234  2018/03/02

我尝试了以下方法,但没有一个起作用:

re.sub('^\\w+:\\w+', '', df["Description"].astype(str))
re.sub('^\\w+:\\w+', '', df["Description"].astype("str"))

我收到以下错误消息:

Traceback (most recent call last):
  File "C:/Users/fff/PycharmProjects/Test/Test.py", line 17, in <module>
    re.sub('^\\w+:\\w+', '', df["Description"].astype("str"))
  File "C:\Users\fff\AppData\Local\Programs\Python\Python36-32\lib\re.py", line 191, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

有人可以帮忙吗?

最佳答案

以下作品:

df['Description'] = df["Description"].str.replace(r'^\w+:\w+', '')


>>> df
                  Description      ID        Date
0    Here comes the first row  id_112  2018/03/02
1   Here comes the second row  id_115  2018/03/02
2    Here comes the third row  id_234  2018/03/02

关于python - 从列中删除带冒号的单词 - 为什么它不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49265699/

相关文章:

java - 如何在Java中使用python代码?

python - 是否有推荐的做法或框架来实现 google-app-engine db.Model/ndb.Model 的记录级权限)?

java - 检查字符串是否包含 CJK(中文)字符

java - 在字符串中查找子字符串的位置(不是 indexOf)

python - SQL命令更新表中的列值

python - 为什么对 `fit` 的第二个 `GridSearchCV` 调用会无休止地工作?

java - 正则表达式不起作用

python - 正则表达式用于解析带引号的子字符串的查询并返回单个单词的嵌套列表

Java:防止编码字符串的自动解码

c - 读取文件行,将每一行放入一个数组中,然后打印