gpt4 book ai didi

python - 根据应用于另一个数组的 bool 表达式选择一个数组的值

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:28 25 4
gpt4 key购买 nike

从以下数组开始

array([ nan,  nan,  nan,   1.,  nan,  nan,   0.,  nan,  nan])

它是这样生成的:

import numpy as np
row = np.array([ np.nan, np.nan, np.nan, 1., np.nan, np.nan, 0., np.nan, np.nan])

我想获取排序数组的索引,然后排除 nans。在这种情况下,我想得到 [6,3]

我想出了以下方法来做到这一点:

vals = np.sort(row)
inds = np.argsort(row)

def select_index_by_value(indices, values):
selected_indices = []
for i in range(len(indices)):
if not np.isnan(values[i]):
selected_indices.append(indices[i])
return selected_indices

selected_inds = select_index_by_value(inds, vals)

现在 selected_inds[6,3]。然而,这似乎是相当多的代码行来实现一些简单的事情。有没有更短的方法可以做到这一点?

最佳答案

你可以这样做 -

# Store non-NaN indices
idx = np.where(~np.isnan(row))[0]

# Select non-NaN elements, perform argsort and use those argsort
# indices to re-order non-NaN indices as final output
out = idx[row[idx].argsort()]

关于python - 根据应用于另一个数组的 bool 表达式选择一个数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38674562/

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