【问题标题】:Combing year and month column only to make date pandas仅结合年月列来制作日期熊猫
【发布时间】:2018-04-24 07:21:02
【问题描述】:

我需要一些帮助我目前有一个数据框,它有两个单独的数字格式的年和月列,我只想将这些列转换为日期。 例如 12-2017

有人知道怎么做吗? 任何帮助将不胜感激!!!

【问题讨论】:

    标签: python python-2.7 python-3.x pandas jupyter-notebook


    【解决方案1】:

    使用pd.to_datetime

    设置

    df = pd.DataFrame(dict(
        year=[2001, 2003, 2014, 1996],
        month=[5, 12, 2, 7],
        other=list('WXYZ')
    ))
    
    df
    
       month other  year
    0      5     W  2001
    1     12     X  2003
    2      2     Y  2014
    3      7     Z  1996
    

    解决方案

    df = df.assign(Date=pd.to_datetime(df[['year', 'month']].assign(day=1)))
    
    df
    
       month other  year       Date
    0      5     W  2001 2001-05-01
    1     12     X  2003 2003-12-01
    2      2     Y  2014 2014-02-01
    3      7     Z  1996 1996-07-01
    

    【讨论】:

    • 不幸的是,当我使用上述代码时出现错误。错误状态“ValueError:额外的键已传递给日期时间组合”你对如何解决这个问题有什么建议吗?
    • 这消除了我的错误,但是如何让它显示在我的数据框中?
    • @Harry 重新分配给 df
    • 我该怎么做?
    • 我当前的代码如下所示: import pandas as pd import numpy as np import datetime df=pd.read_csv("Health.csv") df.assign(Date=pd.to_datetime(df[[ '年', '月']].assign(day=1))) df
    猜你喜欢
    • 2019-02-20
    • 1970-01-01
    • 2018-04-21
    • 2016-07-27
    • 2020-01-24
    • 2019-09-10
    • 2016-06-24
    • 2020-12-21
    • 2020-10-06
    相关资源
    最近更新 更多