1

I was trying this simple 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]]
1
  • 1
    10 questions - 0 accepted answers. Just saying... Commented Sep 27, 2011 at 23:04

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response, I would not have figured that alone, and yes this seems to be a strange behavior as you said.
@JustInTime - then accept this answer (and also those in other questions) please.
I've just run into this problem and discovered this workaround, too. The basic issue seems to be that doing it one way results in a copy, the other a view. It's not clear to me how you are supposed to know, though, other than trying. I found some more info here: stackoverflow.com/questions/3058602/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.