【问题标题】:Combining dataframe year and month into new object Python将数据框年份和月份组合到新对象Python中
【发布时间】:2019-04-15 17:10:01
【问题描述】:

我有一个数据框,其中包含单独的年份和月份列,例如:

Year        Month
2001        1
2001        2
2001        3
.
.
2010        1
2010        2
.

使用pd.to_datetime(df[['year', 'month']]) 转换为pd.datetime 需要几天才能匹配格式,所以我收到错误:

ValueError: to assemble mappings requires at least that [year, month, day] be specified: [day] is missing

我觉得我可以用 Day = 1 重复填充一个新列,但我想避免这种情况,因为我只想按年创建一个时间序列。

有没有办法将年月映射到日期以正确绘制图表?

【问题讨论】:

    标签: python python-3.x pandas date dataframe


    【解决方案1】:

    没有一个月只有datetimethingy。

    pd.to_datetime

    assign 使用参数中指定的列创建df 的副本`。

    正如@timgeb 所说:

    说明:df.assign(day=1) 是一种快速创建带有 'day' 列的临时数据框的方法,而无需修改原始数据框。

    pd.to_datetime(df.assign(day=1))
    
    0   2001-01-01
    1   2001-02-01
    2   2001-03-01
    3   2010-01-01
    4   2010-02-01
    dtype: datetime64[ns]
    

    to_period

    您可能想使用to_period

    pd.to_datetime(df.assign(day=1)).dt.to_period('M')
    
    0   2001-01
    1   2001-02
    2   2001-03
    3   2010-01
    4   2010-02
    dtype: object
    

    【讨论】:

    • 解释:df.assign(day=1) 是一种无需修改原始数据框即可创建具有'day' 列的临时数据框的快捷方式。
    • 我有与每年和每月相关的值。我知道这在原始问题中没有得到解决,但是有没有办法在数据框中制作这些临时值?如果我保留原始索引,将其作为单独的 df 切片,然后将它们添加回原始 df,它就可以工作。
    • IIUC: df.assign(MonthPeriod=df[['Year', 'Month']].assign(day=1).dt.to_period('M'))
    • @HelloToEarth 如果这不是您的意思,您需要澄清一下。我确定答案是肯定的,但我需要先了解您的意思(-:
    猜你喜欢
    • 2018-11-23
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多