Pandas日期范围

2024-05-29 03:54:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在绘制一些数据与时间的关系图,希望时间在x轴上。特别是2014年12月3日至16日之间的时间段。时间在我的数据帧索引中,所以我认为这会很简单。我检查了索引,看起来很好:

IV.index[0]
Out[6]: Timestamp('2014-03-12 00:00:00')
IV.index[-1]
Out[5]: Timestamp('2014-12-16 00:00:00')

然而,当我想将刻度定义为日期范围时,会发生一些非常奇怪的事情:

xticks1 = pd.date_range(start=IV.index[0],end=IV.index[-1], freq='7D', normalize=True)

xticks1
Out[8]: 
DatetimeIndex(['2014-03-12', '2014-03-19', '2014-03-26', '2014-04-02',
               '2014-04-09', '2014-04-16', '2014-04-23', '2014-04-30',
               '2014-05-07', '2014-05-14', '2014-05-21', '2014-05-28',
               '2014-06-04', '2014-06-11', '2014-06-18', '2014-06-25',
               '2014-07-02', '2014-07-09', '2014-07-16', '2014-07-23',
               '2014-07-30', '2014-08-06', '2014-08-13', '2014-08-20',
               '2014-08-27', '2014-09-03', '2014-09-10', '2014-09-17',
               '2014-09-24', '2014-10-01', '2014-10-08', '2014-10-15',
               '2014-10-22', '2014-10-29', '2014-11-05', '2014-11-12',
               '2014-11-19', '2014-11-26', '2014-12-03', '2014-12-10'],
              dtype='datetime64[ns]', freq='7D')

我不明白,为什么?我想要我的约会范围['2014-12-03','2014-12-04' etc.]

事实上,现在我注意到,不知何故,第一个日期(十二月三日)的月份和日期互换了!现在是三月十二号!当我将它转换为datetime对象时,有人知道如何解决这个问题吗?我就是这样做的:

IV['DATE'] = pd.to_datetime(IV['DATE'])
IV = IV.set_index("DATE")

Tags: 数据datetimedateindex关系时间绘制out
1条回答
网友
1楼 · 发布于 2024-05-29 03:54:31

你要找的是pd.to\u datetime的'format'参数。观察:

>>> date = '2014-03-12 00:00:00'
>>> x=pd.to_datetime(date)
>>> x
10: Timestamp('2014-03-12 00:00:00')
>>> x.month
6: 3
>>> x=pd.to_datetime(date,format='%Y-%d-%m %H:%M:%S')
>>> x
7: Timestamp('2014-12-03 00:00:00')
>>> x.month
8: 12

熊猫正在假定日期的格式为%Y-%m-%d

相关问题 更多 >

    热门问题