【问题标题】:how to combine seperated date to datetime in a dataframe如何在数据框中将单独的日期与日期时间结合起来
【发布时间】:2017-04-06 17:06:03
【问题描述】:

我有一个数据框,其中包含三列日期(日、月、年)。 我想将这三列合并为一个日期列以供进一步使用。 我想使用日期列在 matplotlib 轴中引用和绘图。

我尝试使用 (lambda x:'%s %2s %2s' % (x['year'],x['month'], x['day']),axis=1) 创建一个新列并使用它,但它会创建一个字符串,所以我使用 matplotlib.dates.datestr2num() 但它也不起作用。

问题摘要

如何组合这三列以在数据框和数据框中用作日期时间 matplotlib?

【问题讨论】:

    标签: python datetime pandas matplotlib dataframe


    【解决方案1】:

    您可以将to_datetime 与子集daymonthyear 一起使用:

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    
    df = pd.DataFrame({'day':[1,2,3,4,3,4,5],
                       'month':[4,5,7,4,5,6,8],
                       'year':[2013,2013,2103,2013,2013,2103,2013],
                       'A':[1,3,5,5,6,7,9],
                       'B':[4,5,6,5,4,3,4]})
    
    #print (df)
    
    #convert to datetime
    df['date'] = pd.to_datetime(df[['day','month','year']])
    print (df)
       A  B  day  month  year       date
    0  1  4    1      4  2013 2013-04-01
    1  3  5    2      5  2013 2013-05-02
    2  5  6    3      7  2103 2103-07-03
    3  5  5    4      4  2013 2013-04-04
    4  6  4    3      5  2013 2013-05-03
    5  7  3    4      6  2103 2103-06-04
    6  9  4    5      8  2013 2013-08-05
    
    #remove columns
    df.drop(['day','month','year'], axis=1, inplace=True)
    #set index from date dolumn - datetimeindex
    df.set_index('date', inplace=True)
    print (df)
                A  B
    date            
    2013-04-01  1  4
    2013-05-02  3  5
    2103-07-03  5  6
    2013-04-04  5  5
    2013-05-03  6  4
    2103-06-04  7  3
    2013-08-05  9  4
    
    #plot and set format of axis x:
    ax = df.plot()
    ticklabels = df.index.strftime('%Y-%m-%d')
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
    plt.show()
    

    【讨论】:

    • 我做了,但我得到了:ValueError: cannot assemble the datetimes: day is out of range for month
    • 你的熊猫版本是什么? pd.show_versions() ?
    • 熊猫版本---熊猫:0.19.1
    • 尝试通过print (df[pd.to_datetime(df[['day','month','year']], errors='coerce').isnull()])测试有问题的行
    • 如果添加error='coerce' to_datetime 将所有有问题的值转换为NaN 则有效,因此如果检查NaN 的位置获取所有行,则无法转换为日期时间。
    【解决方案2】:

    使用字符串:

    import datetime
    datetime.datetime.strptime('<date string>', '%d%m%Y').date()
    

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多