Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

python - Does assignment with advanced indexing copy array data?

I am slowly trying to understand the difference between views and copys in numpy, as well as mutable vs. immutable types.

If I access part of an array with 'advanced indexing' it is supposed to return a copy. This seems to be true:

In [1]: import numpy as np
In [2]: a = np.zeros((3,3))
In [3]: b = np.array(np.identity(3), dtype=bool)

In [4]: c = a[b]

In [5]: c[:] = 9

In [6]: a
Out[6]: 
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

Since c is just a copy, it does not share data and changing it does not mutate a. However, this is what confuses me:

In [7]: a[b] = 1

In [8]: a
Out[8]: 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

So, it seems, even if I use advanced indexing, assignment still treats the thing on the left as a view. Clearly the a in line 2 is the same object/data as the a in line 6, since mutating c has no effect on it.

So my question: is the a in line 8 the same object/data as before (not counting the diagonal of course) or is it a copy? In other words, was a's data copied to the new a, or was its data mutated in place?

For example, is it like:

x = [1,2,3]
x += [4]

or like:

y = (1,2,3)
y += (4,)

I don't know how to check for this because in either case, a.flags.owndata is True. Please feel free to elaborate or answer a different question if I'm thinking about this in a confusing way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you do c = a[b], a.__get_item__ is called with b as its only argument, and whatever gets returned is assigned to c.

When you doa[b] = c, a.__setitem__ is called with b and c as arguments and whatever gets returned is silently discarded.

So despite having the same a[b] syntax, both expressions are doing different things. You could subclass ndarray, overload this two functions, and have them behave differently. As is by default in numpy, the former returns a copy (if b is an array) but the latter modifies a in place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...