【问题标题】:How to extract the year from a column with different date formatted strings如何从具有不同日期格式字符串的列中提取年份
【发布时间】:2020-02-06 02:54:17
【问题描述】:

我有一个数据框列,其中包含不同类型的 字符串,如下所示:

    year
0   1990
1   1998.0
2   2006-02-12

我只想从它们中提取年份并将它们转换为intfloat

    year
0   1990
1   1998
2   2006

【问题讨论】:

  • left(4) 之类的东西可能有用吗?
  • 你只有这些模式吗?
  • @DanielMesejo 是的,他们是

标签: python regex pandas


【解决方案1】:

假设这些是唯一的模式,您可以使用str.extract

import pandas as pd

df = pd.DataFrame(data=['1990','1998.0','2006-02-12'], columns=['year'])

result = df.year.str.extract('^(\d{4})')
print(result)

输出

      0
0  1990
1  1998
2  2006

^(\d{4}) 模式转换为开头字符串的前 4 位数字,因此您基本上是在提取列中每个字符串的前 4 位数字。

【讨论】:

  • 我也试过了,效果很好:df['year'].apply(lambda x: x[:4])
  • df.year.str.slice(0, 4) :)
  • @BKS 你也可以df.year.str[:4]
猜你喜欢
  • 1970-01-01
  • 2021-04-30
  • 2016-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
相关资源
最近更新 更多