我正在尝试根据正则表达式将数据框中的一列设置为另一列的子字符串。一栏有标题,有时还有年份,例如“Temp (2019)”或“Temp”。我需要从该标题中提取年份(如果有的话),然后从原始单词中删除年份。因此,不是将一列作为“Temp (2019)”,而是有两列,一列是“Temp”,另一列是“2019”。如果标题没有单词,则输入 0。regex = r"\(\d{4}\)$"tempYear = df['title'].str[-5:-1]df['year'] = np.where(re.search(regex, df['title']) != None, df['title'].str[-5:-1], "0")现在,当我运行它时,我收到此错误:Exception has occurred: TypeErrorexpected string or bytes-like object File "[path]", line 63, in <module> df['year'] = np.where(re.search(regex, df['title']) != None, df['title'].str[-5:-1], "0")我认为这是因为我使用了第一个条件(如果条件为真),因为它是一个列表(我认为)而不是单个单词。换句话说,if 语句具有多种类型。我不知道如何在没有它的情况下从标题中提取年份。标题,如果有年份,将始终采用“[word] ([year])”格式,年份在末尾,在括号中。我可以轻松做到df['year'] = df['title'].str[-5:-1]但是当没有一年时,这会导致问题。
1 回答

千万里不及你
TA贡献1784条经验 获得超9个赞
在 Pandas 中,str
提供正则表达式处理,而标准库re
模块不能处理 Pandas 系列而不是 numpy 数组。
所以你想要的东西可以更容易地通过熊猫函数获得:
df['year'] = np.where(df.title.str.contains(regex), df['title'].str[-5:-1], "0")
添加回答
举报
0/150
提交
取消