1

我有熊猫系列myS

import pandas as pd

索引是一组仅包含时间的字符串

myS.index

Out[28]: 
Index([u'12:00 AM', u'12:14 AM', u'12:18 AM', u'12:25 AM', u'12:26 AM',
       u'12:37 AM', u'12:41 AM', u'12:47 AM', u'12:55 AM', u'12:59 AM',
       ...
       u'11:00 PM', u'11:02 PM', u'11:09 PM', u'11:18 PM', u'11:25 PM',
       u'11:35 PM', u'11:42 PM', u'11:46 PM', u'11:50 PM', u'11:55 PM'],
      dtype='object', name=u'Time (CET)', length=169)

我可以方便地将其正确转换为日期时间:

myS.index= pd.to_datetime(myS.index, format='%I:%M %p')

但是,所有日期都将设置为1900-01-01

 '1900-01-01 23:50:00', '1900-01-01 23:55:00'],
              dtype='datetime64[ns]',

如果我有可用的日期时间,如何将索引的所有日期重置为所需值,同时保持时间不变?

4

2 回答 2

2

我认为您需要添加Date列,然后转换为datetime

myS.index = pd.to_datetime(myS['Date'].astype(str) + ' ' + myS.index)

或添加标量:

myS.index = pd.to_datetime('2015-01-05' + ' ' + myS.index)

通过评论编辑:

myS.index = pd.to_datetime(str(mydatetime.date()) + ' ' + myS.index, 
                           format='%Y-%m-%d %I:%M %p',errors='coerce')

或使用strftime

myS.index = pd.to_datetime(mydatetime.strftime('%Y-%m-%d') + ' ' + 
                           myS.index, format='%Y-%m-%d %I:%M %p',errors='coerce')

样本:

idx = pd.Index([u'12:00 AM', u'12:14 AM', u'12:18 AM', u'12:25 AM'])
myS = pd.Series(range(4), index=idx)
print (myS)
12:00 AM    0
12:14 AM    1
12:18 AM    2
12:25 AM    3
dtype: int64

mydatetime = pd.datetime.now()
print (mydatetime)
2017-12-18 07:52:26.503385

myS.index = pd.to_datetime(str(mydatetime.date()) + ' ' + 
                           myS.index, format='%Y-%m-%d %I:%M %p',errors='coerce')

print (myS)
2017-12-18 00:00:00    0
2017-12-18 00:14:00    1
2017-12-18 00:18:00    2
2017-12-18 00:25:00    3
dtype: int64
于 2017-12-18T06:44:43.110 回答
1
  1. 在所有时间字符串前面加上您想要的日期字符串。
  2. 使用pd.to_datetime, 为您的日期添加额外的格式字符串。

例如,如果您有2017-03-05 12:18 AM,您的格式字符串将变为%Y-%m-%d %I:%M %p.

myS.index = pd.to_datetime('2017-03-05 ' + myS.index, '%Y-%m-%d %I:%M %p')

(事实证明,默认格式适用于这种情况,因此format='%Y-%m-%d %I:%M %p'是可选的。)

于 2017-12-18T06:44:23.073 回答