将索引从时间字符串转换为毫秒-熊猫时间序列

时间:2018-11-09 08:37:44

标签: python pandas numpy dataframe time-series

我有一个熊猫时间序列ts,可以按照以下说明重新创建

random.seed(111)
rng = pd.date_range(start='2010-01-11', periods=10, freq='W')
ts = pd.Series(np.random.uniform(-10, 10, size=len(rng)), rng).cumsum()

我得到的结果是这样的:

Index                Value
'2018-10-30 00:00:00' 5
'2018-11-30 00:00:00' 9
'2018-12-30 00:00:00' 7
...

如何将ts的索引转换为毫秒?

Index                Value
1540843200000         5
1543521600000         9
1546113600000         7
...

1 个答案:

答案 0 :(得分:1)

将日期时间转换为原始格式-通过转换为ns然后由np.int64除以10**6,最后分配回来:

print (ts)
2010-01-17     9.536558
2010-01-24     7.171763
2010-01-31     7.687922
2010-02-07     5.193187
2010-02-14    -2.815826
2010-02-21    -4.252529
2010-02-28    -7.060655
2010-03-07    -8.430221
2010-03-14    -8.711684
2010-03-21   -15.011056
Freq: W-SUN, dtype: float64

ts.index = ts.index.astype(np.int64) // 10**6
print (ts)
1263686400000     7.747194
1264291200000    14.755361
1264896000000     8.644319
1265500800000    18.253922
1266105600000    13.046097
1266710400000     9.091535
1267315200000    14.309464
1267920000000    15.630323
1268524800000     7.286377
1269129600000     1.859216
dtype: float64