# In[1]
name=['Alice','Bob','Cathy','Doug']
age=[25,45,37,19]
weight=[55.0,85.5,68.0,61.5]
# In[2]
data=np.zeros(4,dtype={'names':('name','age','weight'),'formats':('U10,'i4','f8')})
print(data.dtype)
# Out[2]
[('name', '<U10'), ('age', '<i4'), ('weight', '<f8')]
U10
means Unicode string of maximum length 10, i4
means 4 byte integer, and f8
means 8 byte float.# In[3]
data['name']=name
data['age']=age
data['weight']=weight
print(data)
# Out[3]
[('Alice', 25, 55. ) ('Bob', 45, 85.5) ('Cathy', 37, 68. )
('Doug', 19, 61.5)]
# In[4]
data['name']
# Out[4]
array(['Alice' 'Bob' 'Cathy' 'Doug'], dtype='<U10')
# In[5]
data[data['age']<30]['name']
# Out[5]
array(['Alice', 'Doug'], dtype='<U10')
# In[6]
np.dtype({'names':('name','age','weight'),'formats':('U10','i4','f8')})
# Out[6]
dtype([('name', '<U10'), ('age', '<i4'), ('weight', '<f8')])
# In[7]
np.dtype({'names':('name','age','weight'),'formats':((np.str_,10),int,np.float32)})
# Out[7]
dtype([('name', '<U10'), ('age', '<i8'), ('weight', '<f4')])
# In[8]
np.dtype([('name','S10'),('age','i4'),('weight','f8')])
# Out[8]
dtype([('name', 'S10'), ('age', '<i4'), ('weight', '<f8')])
# In[9]
np.dtype('S10,i4,f8')
# Out[9]
dtype([('f0', 'S10'), ('f1', '<i4'), ('f2', '<f8')])
Numpy data types
Character | Description | Example |
---|---|---|
b | Byte | np.dtype('b') |
i | Signed integer | np.dtype('i4') == np.int32 |
u | Unsigned integer | np.dtype('u1') == np.uint8 |
f | Floating point | np.dtype('f8') == np.int64 |
c | Complex floating point | np.dtype('c16') == np.complex128 |
S,a | String | np.dtype('S5') |
U | Unicode string | np.dtype('U') == np.str_ |
V | Raw data(void) | np.dtype('V') == np.void |
# In[10]
tp=np.dtype([('id','i8'),('mat','f8',(3,3))])
X=np.zeros(1,dtype=tp)
print(X[0])
print(X['mat'][0])
# Out[10]
(0, [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]])
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
X
array consists of an id
and a 3×3 matrix.np.recarray
), which are almost identical to the structured arrays just described# In[11]
data['age']
# Out[11]
array([25, 45, 37, 19], dtype=int32)
# In[12]
data_rec=data.view(np.recarray)
data_rec.age
# Out[12]
array([25, 45, 37, 19], dtype=int32)
In[12]
is that for record arrays, there is some extra overhead involved in accessing the fields.