Pandas adding a time index to a date index

I have a dataframe, Date index type is Timestamp, Time column is datetime.Time:

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

How to convert it to:

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

I wrote code that works, but it is not very 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']
+4
source share
1 answer

You can convert the column first Time to_timedelta, then add to index, dropcolumn Timeand set the index if necessary 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

If the column Timeis equal datetime.time, for me the conversion to is performed first in string(add if necessary :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
+4
source

Source: https://habr.com/ru/post/1666123/


All Articles