I was trying this simpl开发者_StackOverflow中文版e line of assigning codes to a structured array in numpy, I am not quiet sure, but something wrong happens when I assign a matrix to a sub_array in a structured array I created as follows:
new_type = np.dtype('a3,(2,2)u2')
x = np.zeros(5,dtype=new_type)
x[1]['f1'] = np.array([[1,1],[1,1]])
print x
Out[143]:
array([('', [[0, 0], [0, 0]]), ('', [[1, 0], [0, 0]]),
('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]),
('', [[0, 0], [0, 0]])],
dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))])
Shouldn't the second field of the subarray equals at this stage
[[1,1],[1,1]]
I think you want to set things slightly differently. Try:
x['f1'][1] = np.array([[1,1],[1,1]])
which results in:
In [43]: x = np.zeros(5,dtype=new_type)
In [44]: x['f1'][1] = np.array([[1,1],[1,1]])
In [45]: x
Out[45]:
array([('', [[0, 0], [0, 0]]), ('', [[1, 1], [1, 1]]),
('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]),
('', [[0, 0], [0, 0]])],
dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))])
This is not to say that this isn't strange behavior though since both x['f1'][1]
and x[1]['f1']
print the same results, but clearly are different:
In [51]: x['f1'][1]
Out[51]:
array([[1, 1],
[1, 1]], dtype=uint16)
In [52]: x[1]['f1']
Out[52]:
array([[1, 1],
[1, 1]], dtype=uint16)
In [53]: x[1]['f1'] = 2
In [54]: x
Out[54]:
array([('', [[0, 0], [0, 0]]), ('', [[2, 1], [1, 1]]),
('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]),
('', [[0, 0], [0, 0]])],
dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))])
In [55]: x['f1'][1] = 3
In [56]: x
Out[56]:
array([('', [[0, 0], [0, 0]]), ('', [[3, 3], [3, 3]]),
('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]),
('', [[0, 0], [0, 0]])],
dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))])
I'd have to think about it a bit more to figure out exactly what is going on.
精彩评论