This gives me an error:
import numpy as np
x = np.array([[1, 'O', 1]],
dtype=np.dtype([('step', 'int32'),
('symbol', '|S1'),
('index', 'int32')]))
TypeError: expected a readable buffer object
I don't know why this should fail?
Alternatlively, how can I force something like this statement to work?
x = np.array([[1, 'O', 1]])
then
x.dtype = np.dtype([('step', 'int32'),('symbol', '|S1'),('index', 'int32')])
or
x.view(dtype=np.dtype([('step', 'int32'),('symbol', '|S1'),('index', 'int32')]))
both give me
ValueError: new type not compatible with array.
Edit
If I try to enter each record as a tuple, it will think that the triple is a single value, rather than three separate fields? For instance:
import numpy as np
x = np.array([(1, 'O', 1)],
dtype=np.dtype([('step', 'int32'),
('symbol', '|S1'),
('index', 'int32')]))
seems fine until I do this:
import numpy.lib.recfunctions as rec
rec.append_fields(x,'x',x['index']+1)
gives me
TypeError: object of type 'numpy.int32' has no len()
presumably because x.shape
is (1,) rather than (1,3).
Record arrays are structured arrays wrapped using a subclass of ndarray, numpy. recarray , which allows field access by attribute on the array object, and record arrays also use a special datatype, numpy. record , which allows field access by attribute on the individual elements of the array.
NumPy provides an N-dimensional array type, the ndarray, which describes a collection of “items” of the same type. The items can be indexed using for example N integers. All ndarrays are homogeneous: every item takes up the same size block of memory, and all blocks are interpreted in exactly the same way.
Make each row a tuple, not a list:
import numpy as np
x = np.array([(1, 'O', 1)],
dtype=np.dtype([('step', 'int32'),
('symbol', '|S1'),
('index', 'int32')]))
Numpy developer Robert Kern explains:
As a rule, tuples are considered "scalar" records and lists are recursed upon. This rule helps numpy.array() figure out which sequences are records and which are other sequences to be recursed upon; i.e. which sequences create another dimension and which are the atomic elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With