记录数组¶

记录数组(record array)与结构数组类似:

In [1]:

  1. import numpy as np

质点类型:

In [2]:

  1. partical_dtype = np.dtype([('mass', 'float'),
  2. ('velocity', 'float')])

生成记录数组要使用 numpy.rec 里的 fromrecords 方法:

In [3]:

  1. from numpy import rec
  2.  
  3. particals_rec = rec.fromrecords([(1,1), (1,2), (2,1), (1,3)],
  4. dtype = partical_dtype)

In [4]:

  1. particals_rec

Out[4]:

  1. rec.array([(1.0, 1.0), (1.0, 2.0), (2.0, 1.0), (1.0, 3.0)],
  2. dtype=[('mass', '<f8'), ('velocity', '<f8')])

在记录数组中,域可以通过属性来获得:

In [5]:

  1. particals_rec.mass

Out[5]:

  1. array([ 1., 1., 2., 1.])

也可以通过域来查询:

In [6]:

  1. particals_rec['mass']

Out[6]:

  1. array([ 1., 1., 2., 1.])

不过,记录数组的运行效率要比结构化数组要慢一些。

也可以通过将一个结构化数组看成记录数组:

In [7]:

  1. particals = np.array([(1,1), (1,2), (2,1), (1,3)],
  2. dtype = partical_dtype)

使用 view 方法看成 recarray

In [8]:

  1. particals_rec = particals.view(np.recarray)

In [9]:

  1. particals_rec.mass

Out[9]:

  1. array([ 1., 1., 2., 1.])

In [10]:

  1. particals_rec.velocity

Out[10]:

  1. array([ 1., 2., 1., 3.])

对于自定义的类型,可以通过它的 names 属性查看它有哪些域:

In [11]:

  1. particals.dtype.names

Out[11]:

  1. ('mass', 'velocity')

原文: https://nbviewer.jupyter.org/github/lijin-THU/notes-python/blob/master/03-numpy/03.21-record-arrays.ipynb