2

I've written a very simple python numpy code. It have a strange behavior...

from numpy import *
# generate 2 array with 15 random int between 1 and 50
pile = random.randint(1, 50, 15)
pile2 = copy(pile)

print("*** pile2",type(pile2),pile2)
print("tab with fixed values ")
tmp2=array([155,156,157,158,159])
print("tmp2",type(tmp2),tmp2)
pile2[:5]=tmp2
print("pile2",type(pile2),pile2)

print("*** pile",type(pile),pile)
print("flip a part of pile and put in an array")
tmp=pile[4::-1]
print("tmp",type(tmp),tmp)
pile[:5]=tmp
print("pile",type(pile),pile)

When I run this script, it return :

*** pile2 <class 'numpy.ndarray'> [20 23 29 31  8 29  2 44 46 17 11 47 29 43 10]
tab with fixed values 
tmp2 <class 'numpy.ndarray'> [155 156 157 158 159]
pile2 <class 'numpy.ndarray'> [155 156 157 158 159  29   2  44  46  17  11  47  29  43  10]

Ok! pile2 become something like "tmp2[] and pile2[6::]", but for the second...

*** pile <class 'numpy.ndarray'> [20 23 29 31  8 29  2 44 46 17 11 47 29 43 10]
flip a part of pile and put in an array
tmp <class 'numpy.ndarray'> [ 8 31 29 23 20]
pile <class 'numpy.ndarray'> [ 8 31 29 31  8 29  2 44 46 17 11 47 29 43 10]

tmp [ 8 31 29 23 20]

pile [ 8 31 29 31 8 29 2 44 46 17 11 47 29 43 10]

Oh! There is problem with assignement ! What's happens ?

1
  • 1
    I am not able to duplicate this behavior. It is possible that there is an error elsewhere in your code. By the way, try to avoid using from [module] import * as it can cause namespace-related problems. Commented Mar 15, 2012 at 16:12

2 Answers 2

2

I can confirm the behaviour with numpy 1.3.0. I guess this is indeed an old bug. And this:

pile[:5]=tmp.copy() 

solves the issue.

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

Comments

0

Because tmp is a view of pile, when you use it to set the content of pile it can cause problem. I am using NumPy 1.6.1, and cannot duplicate this, so maybe this is fixed in the newest version. If you are using old version, you can try:

tmp=pile[4::-1]
pile[:5]=tmp.copy()

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.