首先样品data
;我猜这是一个nxnx3阵列,具有D型uint8
In [791]: data=np.random.randint(0,256,(8,8,3),dtype=np.uint8)
reshape
方法返回一个新形状的新阵,但并没有改变,在就地:
In [793]: data.reshape(1,-1,3)
data.shape=(1,-1,3)
会这么做就地。但为什么最初1
?
相反:
In [795]: aset={tuple(item) for item in data.reshape(-1,3)}
In [796]: aset
Out[796]:
{(3, 92, 60),
(5, 211, 227),
(6, 185, 183),
(9, 37, 0),
....
In [797]: len(aset)
Out[797]: 64
在我来说,一组64个独特的项目 - 并不奇怪,因为我是如何生成的值
你什么都不做的data.reshape
线和{tuple(item) for item in data[0]}
账户为什么它似乎是在图片的第一行上工作。
我猜selection_data
类似于3项元组,如:
In [801]: selection_data = {tuple(data[1,3,:]), (1,2,3), tuple(data[5,5,:])}
In [802]: selection_data
Out[802]: {(1, 2, 3), (49, 132, 26), (76, 131, 16)}
In [803]: selection_data&aset
Out[803]: {(49, 132, 26), (76, 131, 16)}
你不说,你尝试使用tolist
,但我在生成的元组的猜测。
但奇怪的是,tolist
速度可达转换:
In [808]: timeit {tuple(item) for item in data.reshape(-1,3).tolist()}
10000 loops, best of 3: 57.7 µs per loop
In [809]: timeit {tuple(item) for item in data.reshape(-1,3)}
1000 loops, best of 3: 239 µs per loop
In [815]: timeit data.reshape(-1,3).tolist()
100000 loops, best of 3: 19.8 µs per loop
In [817]: timeit {tuple(item.tolist()) for item in data.reshape(-1,3)}
10000 loops, best of 3: 100 µs per loop
所以这样做的排序列表和设置操作,我们不妨跳转到列表格式的时候了。
numpy
有一些组功能,例如np.in1d
。这只对1d阵列进行操作,但正如在unique row
问题中已经证明的那样,我们可以通过将2d阵列视为结构化阵列来解决这个问题。我不得不反复折腾到目前为止,这得到:
In [880]: dt=np.dtype('uint8,uint8,uint8')
In [881]: data1=data.reshape(-1,3).view(dt).ravel()
In [882]: data1
Out[882]:
array([(41, 145, 254), (138, 144, 7), (192, 241, 203), (42, 177, 215),
(78, 132, 87), (221, 176, 87), (107, 171, 147), (231, 13, 53),
...
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
构造一个选择具有相同结构数组性质:
In [883]: selection=[data[1,3,:],[1,2,3],data[5,5,:]]
In [885]: selection=np.array(selection,np.uint8).view(dt)
In [886]: selection
Out[886]:
array([[(49, 132, 26)],
[(1, 2, 3)],
[(76, 131, 16)]],
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
所以在selection
的物品也在data1
发现是:
In [888]: np.in1d(selection,data1)
Out[888]: array([ True, False, True], dtype=bool)
以及data1
中正在选择的项目有:
In [890]: np.where(np.in1d(data1,selection))
Out[890]: (array([11, 45], dtype=int32),)
或拆开的形状
In [891]: np.where(np.in1d(data1,selection).reshape(8,8))
Out[891]: (array([1, 5], dtype=int32), array([3, 5], dtype=int32))
相同的(1,3)和我用于产生selection
(5,5)的项目。
的in1d
时序为竞争力:
In [892]: %%timeit
...: data1=data.reshape(-1,3).view(dt).ravel()
...: np.in1d(data1,selection)
...:
10000 loops, best of 3: 65.7 µs per loop
In [894]: timeit selection_data&{tuple(item) for item in data.reshape(-1,3).tolist()}
10000 loops, best of 3: 91.5 µs per loop
预计'tolist'会加快转换速度。 Numpy对象将数据存储为原始值,而不是python对象。这意味着每个来自python的访问都需要numpy来为值创建一个包装对象。这也在迭代时完成。 'tolist'方法在一个优化的C循环中创建所有的包装,并将它们放到一个python列表中,随后的迭代是通过一个很快的python列表,因为它不需要创建包装对象。 – Bakuriu