l.stewie
l.stewie

Reputation: 41

In Python how do I make a copy of a numpy Matrix column such that any further operations to the copy does not affect the original matrix?

I would normally copy a whole matrix as follows:

from copy import copy, deepcopy
b=np.array([[2,3],[1,2]])
a = np.empty_like (b)
a[:] = b

(Note a and b are not what I am using in my code and are just made up for this example). But how do I copy just the first column (or any selected column) of a matrix so that when operated on it does not affect the original column?

PS. I am new so sorry If I am making a really stupid error but I really have searched for the solution a long time

Upvotes: 3

Views: 173

Answers (1)

Kasravnd
Kasravnd

Reputation: 107307

Just use indexing to slice a column then use copy() attribute of array object to create a copy:

>>> b=np.array([[2,3],[1,2]])
>>> b
array([[2, 3],
       [1, 2]])
>>> a = b[:,0].copy()
>>> a
array([2, 1])
>>> a += 2
>>> a
array([4, 3])
>>> b
array([[2, 3],
       [1, 2]])

Upvotes: 1

Related Questions