如何将numpy数组从numpy.int64转换为datetime?

时间:2018-12-10 17:30:28

标签: python python-3.x numpy datetime

我有以下类型为using UnityEngine; public class GoToTouch : MonoBehaviour { public Camera cam;//put your main camera here public float speed;//Speed of movement Vector3 LastTouch; void Start() { LastTouch = Vector3.zero; } void Update() { //We check for new touches etch frame if (Input.touchCount> 0) LastTouch = Input.touches[0].rawPosition; //We move towards the last touch if(LastTouch != Vector3.zero)transform.position= Vector3.Lerp(transform.position,cam.ScreenToWorldPoint(LastTouch),speed*Time.DeltaTime); } }

的数组
<class 'numpy.ndarray'>

如何将其成分从当前类型array([20181010, 20181031, 20181116, 20181012, 20181005, 20181008, 20181130, 20181011, 20181005, 20181116]) 转换为<class 'numpy.int64'>中的日期时间?我想找到一种快速的方法,我的理解是,使用循环或列表理解以及将此numpy转换为numpy.arraypandas会比较慢。

如果我错了,请纠正我。

P.S。这个问题可能已经在某个地方回答了,但是我找不到一个可行的解决方案。

1 个答案:

答案 0 :(得分:2)

pandas对可以视为日期的概念有更好的理解:

import numpy as np
import pandas as pd
arr = np.array([20181010, 20181031, 20181116, 20181012, 20181005, 
                20181008, 20181130, 20181011, 20181005, 20181116])
pd.to_datetime(arr.astype(str)).values

将其运行在一组10,000,000个条目上:

%%prun import numpy as np; import pandas as pd
lst = [20181010, 20181031, 20181116, 20181012, 20181005, 
       20181008, 20181130, 20181011, 20181005, 20181116]*1000000
arr = np.array(lst)
arr_str = arr.astype(str)
pd.to_datetime(arr_str).values

产生{p}的prun

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    8.977    8.977    8.977    8.977 {method 'astype' of 'numpy.ndarray' objects}
        1    4.394    4.394    4.394    4.394 {built-in method pandas._libs.tslib.array_to_datetime}
        2    2.344    1.172    2.344    1.172 {built-in method pandas._libs.algos.ensure_object}
        4    0.918    0.229    0.918    0.229 {built-in method numpy.core.multiarray.array}
        1    0.313    0.313    7.053    7.053 datetimes.py:106(to_datetime)
...

效率足够高。