python - 如何从时间索引中获取最后一毫秒?

标签 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 中做到这一点,而不必将时间戳转换为字符串并获取最后一个字符呢?是否有基于时间的方法来执行此操作?

谢谢!

最佳答案

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

关于python - 如何从时间索引中获取最后一毫秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45925957/

相关文章:

python - 如何将类的实例传递到其构造函数中的属性并让这些属性访问已初始化的属性?

python - 如何验证从 Cognito CustomUI 登录页面返回的 AWS Cognito session 代码

python - 无法编译需要 C99 编译器 (AFAIU) 的 pyethash python 包。错误 - 无法打开包含文件 : 'alloca.h'

python - 使用 python 构建拓扑时出现映射错误

python - pandas argsort 的有趣结果

python - 附加来自不同文件的数组并向数据插入一列

python - 将训练数据的四分位数切割应用于测试数据

python - 如何将 XML 文件转换为 Pandas 数据框

python - 如何按列名称对行进行分组并按日期时间对行进行排序

python - 使用精确开始周期重新采样数据帧