I have a list of float
numbers and I would like to convert it to numpy array
so I can use numpy.where()
to get indices of elements that are bigger than 0.0 (not zero)
I tried this, but with no luck:
import numpy as np
arr = np.asarray(enumerate(grade_list))
g_indices = np.where(arr[1] > 0)[0]
Edit:
is dtype=float
needed?
You don't need numpy arrays to filter lists.
List comprehensions
List comprehensions are a really powerful tool to write readable and short code:
gives
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13]
. This is a standard Python list. This list can be converted to a numpy array afterwards, if necessary.Numpy
If you really want to use
numpy.where
, you should skip theenumerate
:gives
[ 0 1 2 3 4 5 6 7 8 9 12 13]
.Performance comparision
If you only need this for a small list (e.g. < 100), the list comprehension is the fastest way to do it. Using numpys where is significantly faster than using a list comprehension first and then converting it to a numpy array (for list length of 1000):
These results were created with the following script: