gpt4 book ai didi

python - 在 Pandas 中创建年份列

转载 作者:太空宇宙 更新时间:2023-11-04 00:03:41 24 4
gpt4 key购买 nike

我正在尝试创建一个年份列,其中的年份取 self 的数据框中的标题列。此代码有效,但列 dtype 是对象。例如,在第 1 行中,年份显示为 [2013]。

我该怎么做,但要将列 dtype 更改为 float ?

year_list = []

for i in range(title_length):
year = re.findall('\d{4}', wine['title'][i])
year_list.append(year)

wine['year'] = year_list

这是我的数据框的头部:

country   designation     points    province               title             year
Italy Vulkà Bianco 87 Sicily Nicosia 2013 Vulkà Bianco [2013]

最佳答案

您可以使用 str.extract() 代替返回字符串列表的 re.findall:

wine['year'] = wine['title'].str.extract(r'\b(\d{4})\b')

或者,如果您只想匹配 1900-2000 年:

wine['year'] = wine['title'].str.extract(r'\b((?:19|20)\d{2})\b')

请注意,str.extract 中的模式必须包含至少 1 个捕获组,其值将用于填充新列。只会考虑第一个匹配项,因此如果需要,您可能需要稍后精确确定上下文。

我建议在 \d{4} 模式周围使用单词边界 \b 来将 4 位数字 block 匹配为整个单词,并避免像 这样的字符串中的部分匹配>1234567890

关于python - 在 Pandas 中创建年份列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54953166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com