4
from numpy import *
a=array([0.,0.001,0.002])
b=array([[1,11],[2,22],[3,33]])
b[:,1]=a
print b

I expected as a result:

array([[  1. , 0. ],[  2. ,  0.001 ],[  3. , 0.002 ]])

But I got:

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

To obtain desired result I had to type:

from numpy import *
a=array([0.,0.001,0.002])
b=array([[1,11],[2,22],[3,33]])
b=b.astype(float)
b[:,1]=a
print b

Is it a bug? Shouldn't assignment automatically make numpy array a float type?

1
  • 1
    It's not really possible to change the dtype of an array in-place. The internal memory layout of an int32 array isn't compatible with that of a float64 array. Commented Feb 2, 2014 at 0:05

2 Answers 2

3

No, it is not a bug. From docs:

Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints)

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

3 Comments

Thanks! I think this fact is not well known, I mean I was googling quite a lot, and in simple tutorials for beginners, and even for intermediate users that is not exposed :) Thank you once again :)
It is actually a very core concept in programming, IMHO, not only in Python. The differences are there across languages, but it's pretty much present. It's not often you'll see them in tutorials, but they are covered extensively in the beginning parts of most good books, regardless of language covered. :)
Yeah, syntax is not everything I guess, the basics of hardware handling are also important. Could you (BK201) mention some title of such a good book? :)
0

The behavior seems intuitive to me, array b remains the same dtype before and after the assignment, so dtype of a needs to be changed to dtype of b.

>>> a.astype(b.dtype) # and when you convert a to dtype of b you get:
array([0, 0, 0])
>>> 
>>> b[:, 1] = a.astype(b.dtype) # I believe this is what is going on under the hood.
>>> b
array([[1, 0],
       [2, 0],
       [3, 0]])

Comments

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.