【发布时间】:2019-11-21 00:32:33
【问题描述】:
我已搜索以下问题的答案,但尚未找到答案。我有一个像这个小例子这样的大型数据集:
df =
A B
1 I bought 3 apples in 2013
3 I went to the store in 2020 and got milk
1 In 2015 and 2019 I went on holiday to Spain
2 When I was 17, in 2014 I got a new car
3 I got my present in 2018 and it broke down in 2019
我想要提取 > 1950 的所有值并将其作为最终结果:
A B C
1 I bought 3 apples in 2013 2013
3 I went to the store in 2020 and got milk 2020
1 In 2015 and 2019 I went on holiday to Spain 2015_2019
2 When I was 17, in 2014 I got a new car 2014
3 I got my present in 2018 and it broke down in 2019 2018_2019
我尝试先提取值,但没有进一步:
df["C"] = df["B"].str.extract('(\d+)').astype(int)
df["C"] = df["B"].apply(lambda x: re.search(r'\d+', x).group())
但我得到的只是错误消息(几周前我才开始使用 python 并使用文本..)。有人可以帮我吗?
【问题讨论】:
-
应该包括 1950 年吗?您还想提取
19555和更多位数的数字吗? -
你可以使用this
-
@WiktorStribiżew 我还没有走那么远,但我在想:因为我需要它发生的年份,在我提取它们之后过滤数字 >1950 我会得到年份和松散其他无用的值。
-
我会使用
df["C"] = df["B"].str.findall(r'(?<!\d)(?:19[5-9]\d|[2-9]\d{3}|\d{5,})(?!\d)').str.join('_')之类的东西,其中还包括 1950 和 5+ 位数字。 -
如果您只需要 4 位数的年份,请从上面删除
|\d{5,}。要排除1950,请在(?<!\d)之后添加(?!1950)/(?!1950(?!\d))。仅当您的输入完全混乱时才使用它。