3

I am learning python so please bear with me. I have been trying to get a datetime variable into a numpy array, but have not been able to figure out how. I need to calculate differences between times for each index later on, so I didn't know if I should put the datetime variable into the array, or convert it to another data type. I get the error:

'NoneType' object does not support item assignment

Is my dtype variable constructed correctly? This says nothing about datetime type.

import numpy as np
from liblas import file

f = file.File(project_file, mode = 'r')
num_points = int(f.__len())
# dtype should be [float, float, float, int, int, datetime]
dt = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('i', 'u2'), ('c', 'u1'), ('time', 'datetime64')]
xyzict = np.empty(shape=(num_points, 6), dtype = dt)

# Load all points into numpy array
counter = 0
for p in f:
    newrow = [p.x, p.y, p.z, p.i, p.c, p.time]
    xyzict[counter] = newrow     
    counter += 1

Thanks in advance

EDIT: I should note that I plan on sorting the array by date before proceeding.

p.time is in the following format:

>>>p.time
datetime.datetime(1971, 6, 26, 19, 37, 12, 713269)
>>>str(p.time)
'1971-06-26 19:37:12.713275'
4

1 回答 1

4

我真的不明白你是如何datetime从你的文件中获取一个对象的,或者是什么p,但假设你有一个元组列表(不是列表,请参阅我上面的评论),你可以在一个中完成所有设置步:

dat = [(.5, .5, .5, 0, 34, datetime.datetime(1971, 6, 26, 19, 37, 12, 713269)),
       (.3, .3, .6, 1, 23, datetime.datetime(1971, 6, 26, 19, 34, 23, 345293))]

dt = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('i', 'u2'), ('c', 'u1'), ('time', 'datetime64[us]')]

datarr = np.array(dat, dt)

然后您可以按名称访问字段:

>>> datarr['time']
array(['1971-06-26T15:37:12.713269-0400', '1971-06-26T15:34:23.345293-0400'], dtype='datetime64[us]')

或按字段排序:

>>> np.sort(datarr, order='time')
array([ (0.3, 0.3, 0.6, 1, 23, datetime.datetime(1971, 6, 26, 19, 34, 23, 345293)),
        (0.5, 0.5, 0.5, 0, 34, datetime.datetime(1971, 6, 26, 19, 37, 12, 713269))], 
  dtype=[('x', '<f4'), ('y', '<f4'), ('z', '<f4'), ('i', '<u2'), ('c', 'u1'), ('time', '<M8[us]')])
于 2013-11-08T23:02:38.473 回答