我有一个二维数组。我需要过滤数组中具有特定索引值的行。这些值来自列表。
这是一个例子。
我的数据:
arr= [[ 1.681, 1.365, 0.105, 0.109, 0.50],
[ 1.681, 1.365, 0.105, 0.109, 0.51],
[ 1.681, 1.365, 0.105, 0.109, 0.52],
[ 1.681, 1.365, 0.105, 0.109, 0.53],
[ 1.681, 1.365, 0.105, 0.109, 0.54],
[ 1.681, 1.365, 0.105, 0.109, 0.55],
[ 1.681, 1.365, 0.105, 0.109, 0.56],
[ 1.681, 1.365, 0.105, 0.109, 0.57],
[ 1.681, 1.365, 0.105, 0.109, 0.58],
[ 1.681, 1.365, 0.105, 0.109, 0.59],
[ 1.681, 1.365, 0.105, 0.109, 0.60]]
假设我想过滤最后一个条目来自列表 0.5、0.55、0.6 的行。
我试过如下制作面具:
>>> mask= arr['f4'] in [0.5, 0.55, 0.6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> mask= arr['f4']==0.5 or arr['f4']==0.55 or arr['f4']==0.6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>>
如图所示,它不起作用。
期望的输出是:
>>> arr_mask
[[1.681, 1.365, 0.105, 0.109, 0.5], [1.681, 1.365, 0.105, 0.109, 0.55], [1.681, 1.365, 0.105, 0.109, 0.6]]
感谢您的反馈。
编辑 1: 有一个关于“f4”的问题。这似乎来 self 将文件中的数据读入数组的方式。
>>> arr= np.genfromtxt('data.rpt',dtype=None)
>>> arr
array([ ('tag', 1.681, 1.365, 0.105, 0.109, 0.5),
('tag', 1.681, 1.365, 0.105, 0.109, 0.51),
('tag', 1.681, 1.365, 0.105, 0.109, 0.52),
('tag', 1.681, 1.365, 0.105, 0.109, 0.53),
('tag', 1.681, 1.365, 0.105, 0.109, 0.54),
('tag', 1.681, 1.365, 0.105, 0.109, 0.55),
('tag', 1.681, 1.365, 0.105, 0.109, 0.56),
('tag', 1.681, 1.365, 0.105, 0.109, 0.57),
('tag', 1.681, 1.365, 0.105, 0.109, 0.58),
('tag', 1.681, 1.365, 0.105, 0.109, 0.59),
('tag', 1.681, 1.365, 0.105, 0.109, 0.6)],
dtype=[('f0', 'S837'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8'), ('f5', '<f8')])
EDIT02:
尝试了 jp_data_analysis 的建议,但它不起作用。可能是从文件读取数组的来源造成的?
>>> arr_np = np.array(arr)
>>> search = np.array([0.50, 0.55, 0.60])
>>> arr_np[np.in1d(arr_np[:,-1], search)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: too many indices for array
>>>
请您参考如下方法:
基本上来自 np.where 文档
import numpy as np
arr= np.array([[ 1.681, 1.365, 0.105, 0.109, 0.50],
[ 1.681, 1.365, 0.105, 0.109, 0.51],
[ 1.681, 1.365, 0.105, 0.109, 0.52],
[ 1.681, 1.365, 0.105, 0.109, 0.53],
[ 1.681, 1.365, 0.105, 0.109, 0.54],
[ 1.681, 1.365, 0.105, 0.109, 0.55],
[ 1.681, 1.365, 0.105, 0.109, 0.56],
[ 1.681, 1.365, 0.105, 0.109, 0.57],
[ 1.681, 1.365, 0.105, 0.109, 0.58],
[ 1.681, 1.365, 0.105, 0.109, 0.59],
[ 1.681, 1.365, 0.105, 0.109, 0.60]])
ix = np.isin(arr[:,-1], [0.5,0.55,0.6])
np.where(ix)
Out[107]: (array([ 0, 5, 10], dtype=int64),)
arr[np.where(ix),:]
Out[108]:
array([[[ 1.681, 1.365, 0.105, 0.109, 0.5 ],
[ 1.681, 1.365, 0.105, 0.109, 0.55 ],
[ 1.681, 1.365, 0.105, 0.109, 0.6 ]]])
