(编辑为 EOL 建议在回答问题时更具体。)
创建 0-dim 数组(我也没有找到标量构造函数。)
>>> data0 = np.array(('2011-09-20', 0), dtype=[('start date', 'S11'), ('n', int)])
>>> data0.ndim
0
访问 0-dim 数组中的元素
>>> type(data0[()])
<class 'numpy.void'>
>>> data0[()][0]
b'2011-09-20'
>>> data0[()]['start date']
b'2011-09-20'
>>> #There is also an item() method, which however returns the element as python type
>>> type(data0.item())
<class 'tuple'>
我认为最简单的方法是将结构化数组(或recarrays)视为元组的列表或数组,索引按名称选择列,按整数选择行。
>>> tupleli = [('2011-09-2%s' % i, i) for i in range(5)]
>>> tupleli
[('2011-09-20', 0), ('2011-09-21', 1), ('2011-09-22', 2), ('2011-09-23', 3), ('2011-09-24', 4)]
>>> dt = dtype=[('start date', '|S11'), ('n', np.int64)]
>>> dt
[('start date', '|S11'), ('n', <class 'numpy.int64'>)]
零维数组,元素为元组,即一条记录,已更改:不是标量元素,见末尾
>>> data1 = np.array(tupleli[0], dtype=dt)
>>> data1.shape
()
>>> data1['start date']
array(b'2011-09-20',
dtype='|S11')
>>> data1['n']
array(0, dtype=int64)
一个元素的数组
>>> data2 = np.array([tupleli[0]], dtype=dt)
>>> data2.shape
(1,)
>>> data2[0]
(b'2011-09-20', 0)
一维数组
>>> data3 = np.array(tupleli, dtype=dt)
>>> data3.shape
(5,)
>>> data3[2]
(b'2011-09-22', 2)
>>> data3['start date']
array([b'2011-09-20', b'2011-09-21', b'2011-09-22', b'2011-09-23',
b'2011-09-24'],
dtype='|S11')
>>> data3['n']
array([0, 1, 2, 3, 4], dtype=int64)
直接索引到单个记录,与 EOL 的示例相同,我不知道它有效
>>> data3[2][1]
2
>>> data3[2][0]
b'2011-09-22'
>>> data3[2]['n']
2
>>> data3[2]['start date']
b'2011-09-22'
试图理解EOL的例子:标量元素和零维数组是不同的
>>> type(data1)
<class 'numpy.ndarray'>
>>> type(data1[()]) #get element out of 0-dim array
<class 'numpy.void'>
>>> data1[0]
Traceback (most recent call last):
File "<pyshell#98>", line 1, in <module>
data1[0]
IndexError: 0-d arrays can't be indexed
>>> data1[()][0]
b'2011-09-20'
>>> data1.ndim
0
>>> data1[()].ndim
0
(注意:我不小心在打开的 python 3.2 解释器中输入了示例,所以有一个 b'...')