如何从timeindex获取最后一毫秒?

时间:2017-08-28 19:17:48

标签: python pandas

考虑这个例子

idx = [pd.to_datetime('2012-02-01 14:00:00.531') , 
       pd.to_datetime('2012-02-01 14:01:00'),
       pd.to_datetime('2012-03-05 14:01:02.2'),
       pd.to_datetime('2012-03-05 14:01:03.123'),
       pd.to_datetime('2012-03-10 14:02:00'),
       pd.to_datetime('2012-03-11 14:02:00')
       ]

test = pd.DataFrame({'value':[1,2,3,4,5,6]},
                  index = idx)

test
Out[26]: 
                         value
2012-02-01 14:00:00.531      1
2012-02-01 14:01:00.000      2
2012-03-05 14:01:02.200      3
2012-03-05 14:01:03.123      4
2012-03-10 14:02:00.000      5
2012-03-11 14:02:00.000      6

我想提取时间戳的毫秒部分的最后一个数字。那是

test
Out[24]: 
                         last_milli  value
2012-02-01 14:00:00.531           1      1
2012-02-01 14:01:00.000           0      2
2012-03-05 14:01:02.200           0      3
2012-03-05 14:01:03.123           3      4
2012-03-10 14:02:00.000           0      5
2012-03-11 14:02:00.000           0      6

如何在Pandas中完成此操作而不必将时间戳转换为字符串并获取最后一个字符?有没有基于时间的方法呢?

谢谢!

1 个答案:

答案 0 :(得分:4)

test.index.microsecond // 1000 % 10

Int64Index([1, 0, 0, 3, 0, 0], dtype='int64')
test.assign(last_milli=test.index.microsecond // 1000 % 10)

                         value  last_milli
2012-02-01 14:00:00.531      1           1
2012-02-01 14:01:00.000      2           0
2012-03-05 14:01:02.200      3           0
2012-03-05 14:01:03.123      4           3
2012-03-10 14:02:00.000      5           0
2012-03-11 14:02:00.000      6           0