سؤال

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'
هل كانت مفيدة؟

المحلول

I don't really understand how you are getting a datetime object out of your file, or what p is for that matter, but assuming you have a list of tuples (not lists, see my comment above), you can do the setting all in one step:

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)

Then you can access the fields by name:

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

Or sort by field:

>>> 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]')])
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top