Ask Your Question
0

replace values in Numpy array

asked 2013-07-28 23:05:30 +0200

mresimulator gravatar image

updated 2013-07-29 08:26:00 +0200

slelievre gravatar image

Hi experts.

I'm trying to replace some values in a Numpy array. I wanna conserve the unchanged array too.

sage: import numpy as np
sage: N = np.array([[1,2,3],[4,5,6],[8,9,7]])

I call K the new array (with some values repaced):

sage: K = N
sage: K
array([[1, 2, 3],
       [4, 5, 6],
       [8, 9, 7]])
sage: K[1,2] = 9
sage: K
array([[1, 2, 3],
       [4, 5, 9],
       [8, 9, 7]])

But here is the problem: the original array is changed too!!

sage: N
array([[1, 2, 3],
       [4, 5, 9],
       [8, 9, 7]])

How can I change only the array K (and conserve without change the original array N)?

Waiting for your answers.

Thanks a lot!

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
0

answered 2013-07-28 23:28:10 +0200

ppurka gravatar image

You should read the basic numpy tutorial. These introductory things are well explained there. Copying arrays is explained here.

edit flag offensive delete link more
0

answered 2013-07-29 05:16:23 +0200

jack77 gravatar image

Hello,

when assigning N to K, no data is copied, so you working on the original data, To keep the original, you need a deep copy of N:

 K=N.copy()
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2013-07-28 23:05:30 +0200

Seen: 35,778 times

Last updated: Jul 29 '13