3

If I do something like this:

import numpy as np
b=np.array([1,2,3,4,5])
c=np.array([0.6,0.7,0.8,0.9])
b[1:]=c

I get b =

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

It works fine if c only contains integers. But I have fractions. I wish to get something like this:

array([1,0.6,0.7,0.8,0.9])

How can I achieve that?

4 Answers 4

4

Numpy arrays are strongly typed. Make sure your arrays have the same type, like this:

import numpy as np

b = np.array([1, 2, 3, 4, 5])
c = np.array([0.6, 0.7, 0.8, 0.9])

b = b.astype(float)
b[1:] = c

# array([ 1. ,  0.6,  0.7,  0.8,  0.9])

You can, if you wish, even pass types from other arrays, e.g.

b = b.astype(c.dtype)
Sign up to request clarification or add additional context in comments.

1 Comment

Or: b.astype(c.dtype)
2

If you don't know whether the types are matched or not it is more economical to either use .astype with the copy flag set to False or to use np.asanyarray:

>>> b_float = np.arange(5.0)
>>> b_int = np.arange(5)
>>> c = np.arange(0.6, 1.0, 0.1)
>>> 

>>> b = b_float.astype(float)
# astype makes an unnecessary copy
>>> np.shares_memory(b, b_float)
False

# avoid this using the copy flag ...
>>> b = b_float.astype(float, copy=False)
>>> b is b_float
True

# or asanyarray
>>> b = np.asanyarray(b_float, dtype=float)
>>> b is b_float
True

# if the types do not match the flag has no effect
>>> b = b_int.astype(float, copy=False)
>>> np.shares_memory(b, b_int)
False

# likewise asanyarray does make a copy if it must
>>> b = np.asanyarray(b_int, dtype=float)
>>> np.shares_memory(b, b_int)
False

Comments

1

instead of b=np.array([1,2,3,4,5]) which stores elemnts an integers do b=np.array([1,2,3,4,5]).astype(float) which will store elements as float then perform b[1:]=c

Comments

1

The problem is because of the typecasting. It's basically better to have both arrays in the same type before reassigning the items. If it's not possible you can use another function to create your desire array. In this case you can use np.concatenate():

In [16]: np.concatenate((b[:1], c))
Out[16]: array([ 1. ,  0.6,  0.7,  0.8,  0.9])

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.