Mermoz
Mermoz

Reputation: 15484

Numpy matrix modified through a copy

In python 2.7.1 with numpy 1.5.1:

import numpy as np

B = np.matrix([[-float('inf'), 0], [0., 1]])
print B
Bm = B[1:, :]
Bm[:, 1] = float('inf')
print B

returns

[[-inf   0.]
 [  0.   1.]]
[[-inf   0.]
 [  0.  inf]]

which is quite unexpected because I thought Bm was a copy (as in this question).

Any help figuring this out will be appreciated.

Upvotes: 2

Views: 1443

Answers (3)

zhh210
zhh210

Reputation: 408

This is interesting as from jorgeca's example:

a = np.arange(16).reshape((4,4))
a_view = a[::2, ::3]  # basic slicing
a_copy = a[[0, 2], :]  # advanced

My additional comment might be off-topic, but it is surprising that both of the following

a[::2, ::3]+= 1  # basic slicing
a[[0, 2], :]+= 1 # advanced

would make changes on a.

Upvotes: 0

jorgeca
jorgeca

Reputation: 5522

Basic slicing in numpy returns a view, as opposed to slicing Python lists, which copies them.

However, slicing will always copy data if using advanced slicing, just like concatenating or appending numpy arrays.

Compare

a = np.arange(16).reshape((4,4))
a_view = a[::2, ::3]  # basic slicing
a_copy = a[[0, 2], :]  # advanced

Upvotes: 5

Fred Foo
Fred Foo

Reputation: 363627

In my question, it was np.append that was making the copy. Slicing will not copy the array/matrix.

You can make Bm a copy with

Bm = B[1:, :].copy()

Upvotes: 2

Related Questions