Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

need more elaborative explanation for indexed array used as rvalue or lvalue #80

Open
guihao-liang opened this issue Nov 14, 2019 · 2 comments

Comments

@guihao-liang
Copy link

I'm in the process of reading the book for python machine learning (PML). And I followed the PML to learn more about numpy through the Appendix F of this book.

For section F.6, it covers fancy indexing will always return a copy of ndarray. But in section F.7 it shows you can do the assignment to fancy indexed array and the result will be written to the original array. I'm confused.

>>> ary[mask] = 1
>>> ary[~mask] = 0
>>> ary array([0, 0, 1, 1])

That's not consistent with fancy indexing should return a copy instead of a view of the array. If arr[mask] returns a copy, then the following assignment will assign results to the copy instead of the source.

After I did some research, I found the post here explains everything.

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.

I hope @rasbt can elaborately mention the python implementation difference of indexed array being used as rvalue and lvalue.

@rasbt
Copy link
Owner

rasbt commented Nov 14, 2019

Thanks for highlighting this unintuitive behavior. It's definitely worth explaining with regard to left- and right-value.

E.g., when we have

import numpy as np

a = np.array([1, 2, 3, 4, 5])
a[[1, 3]] = 99

a

it returns

array([ 1, 99,  3, 99,  5])

but if we have the fancy indexing on the right, it creates a copy:

a = np.array([1, 2, 3, 4, 5])
b = a[[1, 3]] 
b += 99

a
array([1, 2, 3, 4, 5])

Will leave this issue open to remind myself to update the document in the upcoming days/weeks.

@guihao-liang
Copy link
Author

Perfect! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants