【问题标题】:Convert index from time string to millisecond - Pandas time series将索引从时间字符串转换为毫秒 - Pandas 时间序列
【发布时间】:2019-04-12 19:40:46
【问题描述】:

我有一个熊猫时间系列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
...

【问题讨论】:

    标签: python pandas numpy dataframe time-series


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2013-02-17
      • 1970-01-01
      • 2018-11-01
      • 2016-08-01
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多