假设我有一个熊猫数据框:
Id Book
1 Harry Potter (1997)
2 Of Mice and Men (1937)
3 Babe Ruth Story, The (1948) Drama 948) Babe Ruth Story
如何从列中提取年份?
输出应为:
Id Book Title Year
1 Harry Potter 1997
2 Of Mice and Men 1937
3 Babe Ruth Story, The 1948
到目前为止,我已经尝试过:
movies['year'] = movies['title'].str.extract('([0-9(0-9)]+)', expand=False).str.strip()
和
books['year'] = books['title'].str[-5:-1]
我已经弄乱了一些其他东西,但是还没有开始工作。有什么建议吗?
答案 0 :(得分:3)
一个简单的正则表达式如何?
text = 'Harry Potter (1997)'
re.findall('\((\d{4})\)', text)
# ['1997'] Note that this is a list of "all" the occurrences.
使用数据框,可以这样完成:
text = 'Harry Potter (1997)'
df = pd.DataFrame({'Book': text}, index=[1])
pattern = '\((\d{4})\)'
df['year'] = df.Book.str.extract(pattern, expand=False) #False returns a series
df
# Book year
# 1 Harry Potter (1997) 1997
最后,如果您实际上想将标题和数据分开(在另一个答案中从Philip进行数据帧重建):
df = pd.DataFrame(columns=['Book'], data=[['Harry Potter (1997)'],['Of Mice and Men (1937)'],['Babe Ruth Story, The (1948) Drama 948) Babe Ruth Story']])
sep = df['Book'].str.extract('(.*)\((\d{4})\)', expand=False)
sep # A new df, separated into title and year
# 0 1
# 0 Harry Potter 1997
# 1 Of Mice and Men 1937
# 2 Babe Ruth Story, The 1948
答案 1 :(得分:0)
您可以执行以下操作。
import pandas as pd
df = pd.DataFrame(columns=['id','Book'], data=[[1,'Harry Potter (1997)'],[2,'Of Mice and Men (1937)'],[3,'Babe Ruth Story, The (1948) Drama 948) Babe Ruth Story']])
df['Year'] = df['Book'].str.extract(r'(?!\()\b(\d+){1}')
使用正则表达式查找数字。我使用https://regex101.com/r/Bid0qA/1,这对理解正则表达式的工作原理有很大帮助。
答案 2 :(得分:0)
完整系列的答案实际上是这样的:
books['title'].str.findall('\((\d{4})\)').str.get(0)