2017年6月4日 星期日

[ Python 常見問題 ] Numpy - Get index where value is true

Source From Here
Question
Consider below sample:
>>> import numpy as np
>>> ex = np.arange(10)
>>> e = np.reshape(ex, [5,2])
>>> e
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])

>>> e > 5
array([[False, False],
[False, False],
[False, False],
[ True, True],
[ True, True]], dtype=bool)

I need to find the rows that have true or rows in e whose value are more than 5. I could iterate using a for loop, however, I would like to know if there is a way numpy could do this more efficiently?

How-To
To get the row numbers where at least one item is larger than 5, try numpy.any & numpy.where together:
>>> np.any(e>5, axis=1) // If the row contains any value > 5, True is given. So below show rows 3, 4 contain value > 5
array([False, False, False, True, True], dtype=bool)

>>> np.where([True, False, True]) // Return index where is not zero
(array([0, 2]),)

>>> np.where(np.any(e>5, axis=1))
(array([3, 4]),)


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...