Reputation: 33
I'm doing a project in python which has an array of 600 asteroid measurements (diameter, period, orbit radius). With that information I'd like to make new arrays according the diameter column, the resulting arrays would be diameter intervals of the first one.
If i have this array,
diameter period orbit radius
[[ 19.17 5.71476129 3.19639121]
[ 19.28 4.81234455 2.85035536]
[ 22.77 5.62890294 3.16429553]
[ 4.8 3.29145453 2.21268592]
[ 7.23 2.61331495 1.89724041]
[ 8.17 2.54935585 1.86615697]
[ 260.94 6.49151957 3.47983602]
[ 530. 3.62867648 2.3613482 ]
[ 952.4 4.60562864 2.76813421]]
I'd like to make an array with diameter from 0 to 20
diameter period orbit radius
[[ 19.17 5.71476129 3.19639121]
[ 19.28 4.81234455 2.85035536]
[ 4.8 3.29145453 2.21268592]
[ 7.23 2.61331495 1.89724041]
[ 8.17 2.54935585 1.86615697]]
Upvotes: 3
Views: 100
Reputation: 29711
Assuming you would like to achieve the required matrix using numpy
, you may use numpy.where
to match the conditions and then apply a mask which can be used to index the array to get the required values.
>>>arr[np.where(arr[:, 0] < 20)]
[[ 19.17 5.71476129 3.19639121]
[ 19.28 4.81234455 2.85035536]
[ 4.8 3.29145453 2.21268592]
[ 7.23 2.61331495 1.89724041]
[ 8.17 2.54935585 1.86615697]]
Here, np.where(arr[:, 0] < 20)
checks first column of the array and returns the indices of rows where there's a favourable match which would be used to slice the original array later.
Upvotes: 1
Reputation: 3382
You can easily build new array using the indexing properties of numpy arrays, and that translates into that one liner :
filtered_arr = arr[(arr[:,0]<=20)*(arr[:,0]>=0),:]
or to develop:
#we separate the diameters from the rest
diameter_column= arr[:,0]
#we create a (1D) bool array that match diameter between 0 and 20
diameter_filter=(diameter_column<=20) * (diameter_column>=0)
#we use the boolean array as an index to select the right asteroids
filtered_arr=arr[diameter_filter,:]
Upvotes: 1
Reputation: 1667
Just use a list comprehension to filter it
filtered = [ ast for ast in arr if ast[0]<=20 ]
Upvotes: 4