我有一个9X51100的二维数组(9个不同的数据集,51100个每日文件),我试图取140个数据的年平均值,并将它们附加到一个新的数组中。然而,numpy.append文件需要两个论据,而我最终附加了比我想的更多的东西,我相信。这是我得到的代码和错误。你知道吗
import numpy as np
citydata = ['bcm2.a2.USC00101022.tmax.1960.2099.txt','bcm2.a2.USC00362682.tmax.1960.2099.txt','bcm2.a2.USC00415411.tmax.1960.2099.txt',
'ccsm.a2.USC00101022.tmax.1960.2099.txt','ccsm.a2.USC00362682.tmax.1960.2099.txt','ccsm.a2.USC00415411.tmax.1960.2099.txt',
'pcm.a2.USC00101022.tmax.1960.2099.txt','pcm.a2.USC00362682.tmax.1960.2099.txt','pcm.a2.USC00415411.tmax.1960.2099.txt']
year = np.asanyarray([(np.genfromtxt(item, skip_header=1)[:,0]) for item in citydata])
tmax = np.asanyarray([(np.genfromtxt(item, skip_header=1)[:,3]*(9./5.))+32 for item in citydata])
tmax_avg = np.zeros([9,140]) #initialize averaged array
for i in range(0,8,1):
for yr in years:
toavg = (year == yr)
tmax_avg[i,:] = np.append(tmax_avg,np.average(tmax[toavg]))
ValueError Traceback (most recent call last)
<ipython-input-23-a8a57d128124> in <module>()
8 for yr in years:
9 toavg = (year == yr)
10--> tmax_avg[i,:] = np.append(tmax_avg,np.average(tmax[toavg]))
ValueError: could not broadcast input array from shape (1261) into shape (140)
它似乎只想给我一个140值的数组,而不是一个9X140的数组。追加或循环问题有什么帮助吗?谢谢。你知道吗
有一种相对简单的方法可以使用
np.unique
和np.bincount
对内部for循环进行矢量化。如果我正确地阅读了您的代码,year
是年标签的(9, 51100)
数组,tmax
是相同形状的对应数组。您可以执行以下操作:你可以摆脱
loc
循环,但是如果你只有9个站点,那就不值得了。你知道吗相关问题 更多 >
编程相关推荐