Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 递归选择numpy数组中的元素_Python 2.7_Numpy - Fatal编程技术网

Python 2.7 递归选择numpy数组中的元素

Python 2.7 递归选择numpy数组中的元素,python-2.7,numpy,Python 2.7,Numpy,我有一个文本文件,其中包含全球各点的纬度和温度值。我想取指定纬度间隔(即从南极到北极的每度)之间所有温度点的平均值。这是我目前掌握的代码: data_in = genfromtxt('temperatures.txt', usecols = (0,1)) lat = data_in[:,0] temp = data_in[:,1] in_1N = np.where((lat>=0) & (lat<=1)) # outputs an array of indexes for

我有一个文本文件,其中包含全球各点的纬度和温度值。我想取指定纬度间隔(即从南极到北极的每度)之间所有温度点的平均值。这是我目前掌握的代码:

data_in = genfromtxt('temperatures.txt', usecols = (0,1)) 
lat = data_in[:,0]
temp = data_in[:,1]

in_1N = np.where((lat>=0) & (lat<=1)) # outputs an array of indexes for all latitudes between 0°-1° North
temp_1N = temp[in_1N] # outputs an array of temperature values between 0°-1° North
avg_1N = np.nanmean(temp_1N) # works out the average of temperatures between 0°-1° North

plt.scatter(1, avg_1N) # plots the average temperature against the latitude interval
plt.show()
data\u in=genfromtxt('temperatures.txt',usecols=(0,1))
lat=数据_在[:,0]
温度=数据单位在[:,1]
in_1N=np.其中((lat>=0)和(lat你可以用它把纬度放进箱子里。通常,
np.直方图
只会计算每个箱子里纬度的数量。但是如果你用相关的
temp
值来加权纬度,那么你得到的不是计数,而是temp的和。如果你把temp的和除以箱子计数,你得到的是平均温度in每个垃圾箱:

import numpy as np
import matplotlib.pyplot as plt

# N = 100
# lat = np.linspace(-90, 90, N)
# temp = 50*(1-np.cos(np.linspace(0, 2*np.pi, N)))
# temp[::5] = np.nan
# np.savetxt(filename, np.column_stack([lat, temp]))

lat, temp = np.genfromtxt('temperatures.txt', usecols = (0,1), unpack=True) 
valid = np.isfinite(temp)
lat = lat[valid]
temp = temp[valid]

grid = np.linspace(-90, 90, 40)

count, bin_edges = np.histogram(lat, bins=grid)
temp_sum, bin_edges = np.histogram(lat, bins=grid, weights=temp)
temp_avg = temp_sum / count

plt.plot(bin_edges[1:], temp_avg, 'o')
plt.show()


请注意,如果已安装scipy,则可以替换 对
np.histogram
的两个调用:

count, bin_edges = np.histogram(lat, bins=grid)
temp_sum, bin_edges = np.histogram(lat, bins=grid, weights=temp)
只需拨打一次电话:


谢谢Unutbu。如果温度列中有很多NaN值,这将如何工作?我得到一个带有数据集的空白图表。
import scipy.stats as stats
temp_avg, bin_edges, binnumber = stats.binned_statistic(
    x=lat, values=temp, statistic='mean', bins=grid)