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
436 views
in Technique[技术] by (71.8m points)

python - What is going on behind this numpy selection behavior?

Answering this question, some others and I were actually wrong by considering that the following would work:

Say one has

test = [ [ [0], 1 ],
         [ [1], 1 ]
       ]
import numpy as np
nptest = np.array(test)

What is the reason behind

>>> nptest[:,0]==[1]
array([False, False], dtype=bool)

while one has

>>> nptest[0,0]==[1],nptest[1,0]==[1]
(False, True)


or
>>> nptest==[1]
array([[False,  True],
       [False,  True]], dtype=bool)

or

>>> nptest==1
array([[False,  True],
       [False,  True]], dtype=bool)

Is it the degeneracy in term of dimensions which causes this.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

nptest is a 2D array of object dtype, and the first element of each row is a list.

nptest[:, 0] is a 1D array of object dtype, each of whose elements are lists.

When you do nptest[:,0]==[1], NumPy does not perform an elementwise comparison of each element of nptest[:,0] against the list [1]. It creates as high-dimensional an array as it can from [1], producing the 1D array np.array([1]), and then broadcasts the comparison, comparing each element of nptest[:,0] against the integer 1.

Since no list in nptest[:, 0] is equal to 1, all elements of the result are False.


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

...