我正在尝试根据正则表达式将数据框中的一列设置为另一列的子字符串。一栏有标题,有时还有年份,例如“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: TypeError
expected 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]
但是当没有一年时,这会导致问题。
千万里不及你
相关分类