简体   繁体   中英

Python/Numpy index of array in array

I am just playing around with a particle simulator, I want to use matplotlib with python and numpy to make as realistic a simulator as possible as efficiently as possible (this is purely an exercise in fun with python) and I have a problem trying to calculate the inverse of distances.

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

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

This is 5 particles with positions (x,y) in [0,3]. Now if I want to calculate the distance between one particle (say 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 I do NOT want to take the distance of the particle to itself: (0,0). This has length 0 and the inverse is infinite and is not defined for say gravity or the coloumb force.

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 of the (0,1) particle in the x array. So how do I pick out the position of [0,1] from an array like x? The where() above checks where x is equal to 0 OR 1, not where x is equal to [0,1]. How do I do this "numpylike" without looping?

Ps: How the frack do you copy-paste code into stackoverflow? I mean bad forums have a [code]..[/code] option while here I spend 15 minutes properly indenting code (since tab in chromium on ubuntu simply hops out of the window instead of indenting with 4 whitespaces....) This is VERY annoying.

Edit: Seeing 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)

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

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

Edit2 : any did the trick, it makes more logical sense than all I suppose, thank you!

>>> 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]),)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM