python - 如何从包含文本的熊猫数据框中的列中提取年份(或日期时间)
问题描述
假设我有一个熊猫数据框:
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]
我已经搞砸了一些其他的事情,还没有让它工作。有什么建议么?
解决方案
一个简单的正则表达式怎么样:
text = 'Harry Potter (1997)'
re.findall('\((\d{4})\)', text)
# ['1997'] Note that this is a list of "all" the occurrences.
使用 Dataframe,可以这样完成:
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
推荐阅读
- visual-studio-2017 - Oracle 自定义类向导 Visual Studio 2017
- apache-kafka - Spring Batch + Kafka:KafkaItemReader 永远运行?
- ruby-on-rails - Rails:如何使用 rails app_config 变量作为特征标志,在模型和控制器中设置条件特征
- tensorflow - 谷歌 colab 上的 PYTHONPATH 问题
- python - Dockerfile 构建映像错误:分发包不包含命名空间包的模块或包
- c# - NetTopologySuite.Geometries.MultiPoint 需要有一个 0 args 的构造函数
- swift - AVAudioEngine 输入节点只看到来自连接的聚合音频设备 Swift macOS 的第一个设备输入
- google-bigquery - 无法将数据从 BIg-Query 直接导入 S3
- python - 在 Web 服务器上托管 python 脚本并获取其输出以供进一步使用
- matlab - prepvolume() 的输入参数应该是什么?