【问题标题】:How to convert part of a column to date in Python Pandas?如何在 Python Pandas 中将部分列转换为日期?
【发布时间】:2021-10-15 08:38:18
【问题描述】:

我在 Python 中有 Pandas 数据框,如下所示:

col1
------
00121088645
90110544547
02031134543
110588
  • 我需要从 col1 中的每个值中获取前 6 个元素,并根据它创建日期,并使用此日期创建新列“birthday_date”
  • 如果 col1 中的值以 00 开头,则它是 2000 而不是 1900,例如 90 是 1990 而不是 1890 或任何其他值。我们计算生日日期,所以它只能是 1900 + 或 2000 + :)
  • 请注意!如果 col1 中的值没有 11 个元素,则 col2 中的值必须为“0”

例如:

  • 00121088645 = 2000-12-10
  • 90110544547 = 1990-11-05
  • 02031134543 = 2002-03-11

所以我需要:

col1          birthday_date
-------------------------      
00121088645 | 2000-12-10
90110544547 | 1990-11-05
02031134543 | 2002-03-11
110588      | 0 

【问题讨论】:

  • 例如,对于 21 以内的数字,您如何知道年份是 2010 年还是 1910 年?

标签: python pandas dataframe date


【解决方案1】:

使用 str 访问器获取前 6 个字符,然后将 pd.to_datetime()format='%y%m%d'errors='coerce' 一起使用:

df['birthday_date'] = pd.to_datetime(df['col1'].str[:6], format='%y%m%d', errors='coerce')

#           col1 birthday_date
# 0  00121088645    2000-12-10
# 1  90110544547    1990-11-05
# 2  02031134543    2002-03-11
# 3       110588           NaT

fillna(0)NaT 替换为 0(如果愿意):

df['birthday_date'] = pd.to_datetime(df['col1'].str[:6], format='%y%m%d', errors='coerce').fillna(0)

请注意,我假设 col1 包含字符串(否则不会有任何前导零)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多