将intIndex更改为timedeltaIndex

时间:2018-05-17 14:07:46

标签: python pandas indexing timedelta

我的索引:

Int64Index([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
            17, 18, 19, 20, 21, 22, 23],
           dtype='int64')

我想把它作为:

timedelta64[ns]([0:00, 1:00, 2:00, 3:00 ... %H:%M])

我试过了:

df.index = pd.to_timedelta(df.index)

但这只会改为:00:00:00.000000无处不在。

1 个答案:

答案 0 :(得分:1)

我认为需要to_timedeltaTimedeltaIndex参数unit

df.index = pd.to_timedelta(df.index, unit='H')

或者:

df.index = pd.TimedeltaIndex(df.index, unit='H')

样品:

a = pd.Int64Index([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
            17, 18, 19, 20, 21, 22, 23])

b = pd.to_timedelta(a, unit='H')
print (b)
TimedeltaIndex(['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00',
                '05:00:00', '06:00:00', '07:00:00', '08:00:00', '09:00:00',
                '10:00:00', '11:00:00', '12:00:00', '13:00:00', '14:00:00',
                '15:00:00', '16:00:00', '17:00:00', '18:00:00', '19:00:00',
                '20:00:00', '21:00:00', '22:00:00', '23:00:00'],
               dtype='timedelta64[ns]', freq=None)