Files
ailearning/docs/da/049.md
2020-10-19 21:08:55 +08:00

138 lines
1.6 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 记录数组
记录数组(`record array`)与结构数组类似:
In [1]:
```py
import numpy as np
```
质点类型:
In [2]:
```py
partical_dtype = np.dtype([('mass', 'float'),
('velocity', 'float')])
```
生成记录数组要使用 `numpy.rec` 里的 `fromrecords` 方法:
In [3]:
```py
from numpy import rec
particals_rec = rec.fromrecords([(1,1), (1,2), (2,1), (1,3)],
dtype = partical_dtype)
```
In [4]:
```py
particals_rec
```
Out[4]:
```py
rec.array([(1.0, 1.0), (1.0, 2.0), (2.0, 1.0), (1.0, 3.0)],
dtype=[('mass', '<f8'), ('velocity', '<f8')])
```
在记录数组中,域可以通过属性来获得:
In [5]:
```py
particals_rec.mass
```
Out[5]:
```py
array([ 1., 1., 2., 1.])
```
也可以通过域来查询:
In [6]:
```py
particals_rec['mass']
```
Out[6]:
```py
array([ 1., 1., 2., 1.])
```
不过,记录数组的运行效率要比结构化数组要慢一些。
也可以通过将一个结构化数组看成记录数组:
In [7]:
```py
particals = np.array([(1,1), (1,2), (2,1), (1,3)],
dtype = partical_dtype)
```
使用 `view` 方法看成 `recarray`
In [8]:
```py
particals_rec = particals.view(np.recarray)
```
In [9]:
```py
particals_rec.mass
```
Out[9]:
```py
array([ 1., 1., 2., 1.])
```
In [10]:
```py
particals_rec.velocity
```
Out[10]:
```py
array([ 1., 2., 1., 3.])
```
对于自定义的类型,可以通过它的 `names` 属性查看它有哪些域:
In [11]:
```py
particals.dtype.names
```
Out[11]:
```py
('mass', 'velocity')
```