【问题标题】:Convert string month year (where year is only a two digits) to datetime in pandas将字符串月份年份(年份只有两位数)转换为熊猫中的日期时间
【发布时间】:2022-08-09 15:59:41
【问题描述】:

我有一个数据框,其中有一列 month_year 是一个字符串。其中年份只有两位数。我想将 month_year 列转换为日期时间列。

东风:

month_year
Jan-98
Feb-98
Mar-99
Apr-99
May-99
Oct-00
Nov-00
Jun-01
Aug-03
Sep-08
Dec-21
Jul-22

预期输出:

month_year
01-01-1998
01-02-1998
01-03-1999
01-04-1999
01-05-1999
01-10-2000
01-11-2000
01-06-2001
01-08-2003
01-09-2008
01-12-2021
01-07-2022

我试过下面的代码。

df[\'month_year\'] = pd.to_datetime(df[\'month_year\'])

和

df[\'month_year\'] = pd.to_datetime(df[\'month_year\']).dt.strftime(\'%m-%Y\')

不幸的是,两者都没有工作。

    标签: python-3.x pandas dataframe datetime


    【解决方案1】:

    你很接近,需要格式与 b 月份的前 3 个字母和 y 为年份的 YY 格式:

    df['month_year'] = pd.to_datetime(df['month_year'], format='%b-%y')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2022-09-23
      • 2020-12-21
      • 2018-03-21
      • 2021-07-04
      • 1970-01-01
      相关资源
      最近更新 更多