首页 > 解决方案 > 使用 python ndarray 进行条件索引

问题描述

我有两个python ndarrays pq如下:

import numpy as np
p = np.array([1.        , 1.        , 0.1862802 , 0.19957115, 0.18623812,
       0.1802321 , 0.17464815, 0.16460853, 0.1487719 , 0.12968006,
       0.10464501, 0.07183418, 0.00124706, 0.27353592, 0.81713212,
       0.23720725, 0.21802175, 0.21959138, 0.22401754, 0.22662527,
       0.22777369, 0.23269387, 0.23293132, 0.23374038, 0.24089565,
       0.19958937, 0.23910928, 0.24252447])

q = np.array([[ 1.        ,  1.        ],
       [-0.357316  ,  0.1862802 ],
       [-0.34402505,  0.19957115],
       [-0.35735808,  0.18623812],
       [-0.36336411,  0.1802321 ],
       [-0.36894805,  0.17464815],
       [-0.37898767,  0.16460853],
       [-0.3948243 ,  0.1487719 ],
       [-0.41391615,  0.12968006],
       [-0.4389512 ,  0.10464501],
       [-0.47176202,  0.07183418],
       [-0.54234915,  0.00124706],
       [ 0.27353592,  0.81713212],
       [-0.30638895,  0.23720725],
       [-0.32557445,  0.21802175],
       [-0.32400482,  0.21959138],
       [-0.31957866,  0.22401754],
       [-0.31697093,  0.22662527],
       [-0.31582252,  0.22777369],
       [-0.31090234,  0.23269387],
       [-0.31066488,  0.23293132],
       [-0.30985582,  0.23374038],
       [-0.30270055,  0.24089565],
       [-0.34400684,  0.19958937],
       [-0.30448692,  0.23910928],
       [-0.30107173,  0.24252447]])

我想获得(a)p对应元组的第一个值在哪里的所有q>0和(b)所有这些值的索引p

标签: arrayspython-3.xnumpy

解决方案


使用np.where

idx = np.where(q[:,0]>0)

print(idx, p[idx])

输出:

(array([ 0, 12]),) [1.         0.00124706]

推荐阅读