Python-在for循环中屏蔽?

时间:2018-12-10 18:18:56

标签: python numpy for-loop masking

我有三个数组,r_vals,Tgas_vals和n_vals。它们都是形状为(9998.)的numpy数组。数组具有重复的值,我想遍历r_vals的唯一值并找到Tgas_vals和n_vals的对应值,因此我可以使用最后两个数组来计算加权平均值。这就是我现在所拥有的:

def calc_weighted_average (r_vals,Tgas_vals,n_vals):
        for r in r_vals:
            mask = r == r_vals
            count = 0
            count += 1
            for t in Tgas_vals[mask]:
                print (count, np.average(Tgas_vals[mask]*n_vals[mask]))

    weighted_average = calc_weighted_average (r_vals,Tgas_vals,n_vals)

我遇到的问题是该函数仅循环一次。我是否掩盖了错误的代码,还是在for循环的其他地方出现了问题?

1 个答案:

答案 0 :(得分:0)

我不确定您打算对所有平均值做些什么,所以我将它扔在那里,看看是否有帮助。以下代码将计算一堆加权平均值,每个r_vals的唯一值一个,并将它们存储在字典中(然后打印出来)。

def calc_weighted_average (r_vals, z_vals, Tgas_vals, n_vals):
    weighted_vals = {} #new variable to store rval=>weighted ave.

    for r in np.unique(r_vals):  
        mask = r_vals == r  # I think yours was backwards
        weighted_vals[r] = np.average(Tgas_vals[mask]*n_vals[mask])

    return weighted_vals

weighted_averages = calc_weighted_average (r_vals, z_vals, Tgas_vals, n_vals)

for rval in weighted_averages:
    print ('%i : %0.4f' % (rval, weighted_averages[rval])) #assuming rval is integer

或者,您可能希望以某种方式考虑“ z_vals”。您的问题尚不清楚。