Python: find position of element in array
I have a CSV containing weather data like max and min temperatures, precipitation, longitude and latitude of the weather stations etc. Each category of data is stored in a single column.
I want to find the location of the maximum and minimum temperatures. Finding the max or min is easy: numpy.min(my_temperatures_column)
How can I find the position of where the min or max is located, so I can find the latitude and longitude?
Here is my attempt:
def coldest_location(data):
coldest_temp= numpy.min(mean_temp)
for i in mean_temp:
if mean_temp[i] == -24.6:
print i
Error: List indices must be int
I saved each of the columns of my CSV into variables, so they are all individual lists.
lat = [row[0] for row in weather_data] # latitude
long = [row[1] for row in weather_data] # longitude
mean_temp = [row[2] for row in weather_data] # mean temperature
I have resolved the problem as per the suggestion list.index(x)
mean_temp.index(coldest_temp)
coldest_location=[long[5],lat[5]]
Unsure if asking a second question within a question is proper, but what if there are two locations with the same minimum temperature? How could I find both and their indices?
Have you thought about using Python list's .index(value)
method? It return the index in the list of where the first instance of the value
passed in is found.
Without actually seeing your data it is difficult to say how to find location of max and min in your particular case, but in general, you can search for the locations as follows. This is just a simple example below:
In [9]: a=np.array([5,1,2,3,10,4])
In [10]: np.where(a == a.min())
Out[10]: (array([1]),)
In [11]: np.where(a == a.max())
Out[11]: (array([4]),)
Alternatively, you can also do as follows:
In [19]: a=np.array([5,1,2,3,10,4])
In [20]: a.argmin()
Out[20]: 1
In [21]: a.argmax()
Out[21]: 4
As Aaron states, you can use .index(value)
, but because that will throw an exception if value
is not present, you should handle that case, even if you're sure it will never happen. A couple options are by checking its presence first, such as:
if value in my_list:
value_index = my_list.index(value)
or by catching the exception as in:
try:
value_index = my_list.index(value)
except:
value_index = -1
You can never go wrong with proper error handling.