在numpy数组中查找列表元素等于某事物的行

时间:2017-09-13 08:56:16

标签: python arrays numpy

我有一个带有列表的numpy数组:

[(26, 6, 2, 4, 'Bridge',  1.,  8, '2015-02-02')
 (23, 6, 1, 4, 'Bridge',  1.,  8, '2015-02-02')
 (12, 6, 2, 4, 'Back',  1.,  8, '2015-02-02')
 (23, 6, 3, 4, 'Back',  1.,  8, '2015-02-02')]

我需要通过仅保留将第5个元素设置为'Back'的列表来过滤numpy数组:

[(12, 6, 2, 4, 'Back',  1.,  8, '2015-02-02')
 (23, 6, 3, 4, 'Back',  1.,  8, '2015-02-02')]

1 个答案:

答案 0 :(得分:1)

允许ar

引用给定的numpy数组

所以,

>>> ar = np.array([[26, 6, 2, 4, 'Bridge',  1.,  8, '2015-02-02'],
... [23, 6, 1, 4, 'Bridge',  1.,  8, '2015-02-02'],
... [12, 6, 2, 4, 'Back',  1.,  8, '2015-02-02'],
... [23, 6, 3, 4, 'Back',  1.,  8, '2015-02-02']])
>>> check = np.array([a[4]=='Back' for a in ar])
>>> check
array([False, False,  True,  True], dtype=bool)
>>> ar[check]
array([['12', '6', '2', '4', 'Back', '1.0', '8', '2015-02-02'],
       ['23', '6', '3', '4', 'Back', '1.0', '8', '2015-02-02']],
       dtype='|S11')
>>>

在这里检查numpy数组的布尔索引:https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html