获取大于值的索引并保留值

2024-09-30 22:28:43 发布

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

我有一个2D数组,看起来像这样:

[[0.1, 0.2, 0.4, 0.6, 0.9]
[0.3, 0.7, 0.8, 0.3, 0.9]
[0.7, 0.9, 0.4, 0.6, 0.9]
[0.1, 0.2, 0.6, 0.6, 0.9]]

我想保存数组大于0.6的索引,但我还想保留该位置的值,因此输出为:

[0, 3, 0.6]
[0, 4, 0.9]
[1, 2, 0.7]

等等

为了获得索引,我做了以下操作:

x = np.where(PPCF> 0.6)
high_pc = np.asarray(x).T.tolist()

但如何将该值保持在第三个位置


Tags: np数组wherepchighasarraytolistppcf
3条回答

简单,无循环:

x = np.where(PPCF > 0.6)                                                 # condition to screen values
vals = PPCF[x]                                                           # find values by indices
np.concatenate((np.array(x).T, vals.reshape(vals.size, 1)), axis = 1)    # resulting array

请随意将其转换为列表

这应该起作用:

x = np.where(PPCF> 0.6)
high_pc = np.asarray(x).T.tolist()
for i in high_pc:
    i.append(float(PPCF[i[0],i[1]]))

您可以沿着列和行运行一个循环,检查每个元素是否大于阈值,并将它们保存在列表中

a = [[0.1, 0.2, 0.4, 0.6, 0.9],
[0.3, 0.7, 0.8, 0.3, 0.9],
[0.7, 0.9, 0.4, 0.6, 0.9],
[0.1, 0.2, 0.6, 0.6, 0.9]]

def find_ix(a, threshold = 0.6):
    res_list = []
    for i in range(len(a)):
        for j in range(len(a[i])):
            if a[i][j] >= threshold:
                res_list.append([i, j, a[i][j]])
    return res_list

print("Resulting list = \n ", find_ix(a))

相关问题 更多 >