【问题标题】:Pandas 1.0 create column of months from year and datePandas 1.0 从年份和日期创建月份列
【发布时间】:2020-03-09 14:46:13
【问题描述】:

我有一个数据框df,其值为:

df.iloc[1:4, 7:9]
    Year  Month
38  2020      4
65  2021      4
92  2022      4

我正在尝试创建一个新的MonthIdx 列:

df['MonthIdx'] = pd.to_timedelta(df['Year'], unit='Y') + pd.to_timedelta(df['Month'], unit='M') + pd.to_timedelta(1, unit='D')

但我得到了错误:

ValueError: Units 'M' and 'Y' are no longer supported, as they do not represent unambiguous timedelta values durations.

以下是所需的输出:

df['MonthIdx']
    MonthIdx
38  2020/04/01
65  2021/04/01
92  2022/04/01

【问题讨论】:

    标签: python-3.8 pandas-1.0


    【解决方案1】:

    因此您可以在一系列中填充月份值,然后重新格式化以获得所有值的日期时间:

    month = df.Month.astype(str).str.pad(width=2, side='left', fillchar='0')
    df['MonthIdx'] = pd.to_datetime(pd.Series([int('%d%s' % (x,y)) for x,y in zip(df['Year'],month)]),format='%Y%m')
    

    这会给你:

       Year  Month   MonthIdx
    0  2020      4 2020-04-01
    1  2021      4 2021-04-01
    2  2022      4 2022-04-01
    

    您可以将日期重新格式化为字符串以完全匹配您的格式:

    df['MonthIdx'] = df['MonthIdx'].apply(lambda x: x.strftime('%Y/%m/%d'))
    

    给你:

       Year  Month    MonthIdx
    0  2020      4  2020/04/01
    1  2021      4  2021/04/01
    2  2022      4  2022/04/01
    

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      相关资源
      最近更新 更多