Python / Numpy index of an array in an array

I just play with a particle simulator, I want to use matplotlib with python and numpy to make the simulator as realistic as possible (this is just an exercise in fun with python), and I have a problem trying to calculate the return distances.

I have an array containing the positions of the particles (x, y) like this:

x = random.randint(0,3,10).reshape(5,2) >>> x array([[1, 1], [2, 1], [2, 2], [1, 2], [0, 1]]) 

These are 5 particles with positions (x, y) in [0,3]. Now, if I want to calculate the distance between one particle (for example, a particle with position (0,1)), and the rest I would do something like

 >>>x - [0,1] array([[1, 0], [2, 0], [2, 1], [1, 1], [0, 0]]) 

The problem is that I do not want to take the particle’s distance to myself: (0,0). It has a length of 0, and the inverse is infinite and is not defined for gravity or the strength of a colomb.

So I tried: where (x == [0,1])

 >>>where(x==[0,1]) (array([0, 1, 4, 4]), array([1, 1, 0, 1])) 

Which is not the position (0,1) of the particle in the array x. So how do I select position [0,1] from an array such as x? Where () above checks where x is 0 OR 1, not where x is [0,1]. How to do this "numpylike" without a loop?

Ps: How do you frack copy-paste code in stackoverflow? I mean that on bad forums there is the [code] .. [/ code] option, while here I spend 15 minutes of correctly indenting code (since the tab in chrome on ubuntu just jumps out of the window instead of indents with 4 spaces. ...) This is VERY annoying.

Edit: After reading the first answer , I tried:

 x array([[0, 2], [2, 2], [1, 0], [2, 2], [1, 1]]) >>> all(x==[1,1],axis=1) array([False, False, False, False, True], dtype=bool) >>> all(x!=[1,1], axis=1) array([ True, True, False, True, False], dtype=bool) 

This is not what I was hoping the! = Should return a WITHOUT [1,1] array. But, alas, it misses one (1,0):

 >>>x[all(x!=[1,1], axis=1)] array([[0, 2], [2, 2], [2, 2]]) 

Edit2 : anyone did the trick, it makes more logical sense than all I suppose, thanks!

+4
source share
1 answer
 >>> import numpy as np >>> x=np.array([[1, 1], ... [2, 1], ... [2, 2], ... [1, 2], ... [0, 1]]) >>> np.all(x==[0,1], axis=1) array([False, False, False, False, True], dtype=bool) >>> np.where(np.all(x==[0,1], axis=1)) (array([4]),) >>> np.where(np.any(x!=[0,1], axis=1)) (array([0, 1, 2, 3]),) 
+5
source

Source: https://habr.com/ru/post/1447807/


All Articles