gpt4 book ai didi

python - 使用 for 循环对二维数组进行计算

转载 作者:行者123 更新时间:2023-11-28 18:44:19 25 4
gpt4 key购买 nike

我有一个 9X51100 二维数组(9 个不同的数据集,51,100 个每日文件),我试图对数据进行 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.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 个站点,那可能不值得。

关于python - 使用 for 循环对二维数组进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22254888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com