Python:查找数组中元素的位置 [英] Python: find position of element in array

查看:504
本文介绍了Python:查找数组中元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 CSV 文件,其中包含天气数据,例如最高和最低温度、降水量、气象站的经度和纬度等.每一类数据都存储在一个列中.

我想找到最高和最低温度的位置.找到最大值或最小值很容易:numpy.min(my_temperatures_column)

如何找到最小值或最大值所在的位置,从而找到经纬度?

这是我的尝试:

def Coldest_location(data):最冷的温度= numpy.min(mean_temp)因为我在 mean_temp 中:如果 mean_temp[i] == -24.6:打印我

<块引用>

错误:列表索引必须是整数

我将 CSV 的每一列保存到变量中,因此它们都是单独的列表.

lat = [row[0] for row in weather_data] # 纬度long = [row[1] for row in weather_data] # 经度mean_temp = [row[2] for row in weather_data] # 平均温度

我已经按照建议 list.index(x) 解决了问题

mean_temp.index(coldest_temp)Coldest_location=[long[5],lat[5]]

不确定在问题中问第二个问题是否合适,但如果有两个位置的最低温度相同怎么办?我怎么能找到它们和它们的索引?

解决方案

你有没有想过使用 Python 列表的 .index(value) 方法?它返回在列表中找到传入的 value 的第一个实例的位置的索引.

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.

这篇关于Python:查找数组中元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆