用For-Loop计算二维数组

2024-09-27 19:25:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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的数组。追加或循环问题有什么帮助吗?谢谢。你知道吗


Tags: intxta2fornp数组itemavg
1条回答
网友
1楼 · 发布于 2024-09-27 19:25:15

有一种相对简单的方法可以使用np.uniquenp.bincount对内部for循环进行矢量化。如果我正确地阅读了您的代码,year是年标签的(9, 51100)数组,tmax是相同形状的对应数组。您可以执行以下操作:

tmax_avg = []

count_years = np.unique(year).size

for loc in range(year.shape[0]):
    unq_year, unq_idx = np.unique(year[loc], return_inverse=True)
    unq_sum = np.bincount(unq_idx, weights=tmax[loc], minlength=count_years)
    unq_count = np.bincount(unq_idx, minlength=count_years)
    tmax_avg.append(unq_sum / unq_count)
tmax_avg  = np.vstack(tmax_avg)

你可以摆脱loc循环,但是如果你只有9个站点,那就不值得了。你知道吗

相关问题 更多 >

    热门问题