Pandas将Time列添加到Date索引

时间:2017-01-08 07:17:40

标签: python pandas multiple-columns reshape timedelta

我有一个数据框,日期索引类型是时间戳,时间列是 datetime.Time

            Time  Value
Date
2004-05-01  0:15  3.58507  
2004-05-02  0:30  3.84625
              ...

如何将其转换为:

                    Value
Date
2004-05-01 0:15     3.74618
2004-05-01 0:30     3.58507
2004-05-01 0:45     3.30998

我编写了一个可行的代码,但它不是非常pythonic:

ind = frame.index.get_level_values(0).tolist()
tms = frame['Time']
new_ind = []
for i in range(0, len(ind)):
    tm = tms[i]
    val = ind[i] + timedelta(hours=tm.hour, minutes=tm.minute, seconds=tm.second)
    new_ind.append(val)

frame.index = new_ind
del frame['Time']

1 个答案:

答案 0 :(得分:4)

您可以先转换Time to_timedelta列,然后添加到indexdropTime,如有必要,请设置索引name

df.Time = pd.to_timedelta(df.Time + ':00', unit='h')
df.index = df.index + df.Time
df = df.drop('Time', axis=1)
df.index.name = 'Date'
print (df)
                       Value
Date                        
2004-05-01 00:15:00  3.58507
2004-05-02 00:30:00  3.84625

如果列Timedatetime.time,则我首先将作品投射到string(如有必要,添加:00):

df.Time = pd.to_timedelta(df.Time.astype(str), unit='h')
df.index = df.index + df.Time
df = df.drop('Time', axis=1)
df.index.name = 'Date'
print (df)
                       Value
Date                        
2004-05-01 00:15:00  3.58507
2004-05-02 00:30:00  3.84625