Jos*_*ngs 3 python numpy multidimensional-array
我有一系列的形状(n,t),我想把它当作时间序列n-vectors.
我想知道每个唯一向量的唯一n-vector值t-dimension以及相关t-indices的值.我很乐意使用任何合理的平等定义(例如numpy.unique将采用浮点数)
使用Python循环很容易,t但我希望采用矢量化方法.
在某些特殊情况下,可以通过折叠来完成n-vectors入标量(以及使用numpy.unique上的1D结果),例如,如果你有布尔你可以使用矢量dot与(2**k)转换(布尔向量)为整数向量,但我在寻找相当普遍的解决方案.
如果数组的形状是(t,n) - 所以每个n向量的数据在内存中是连续的 - 你可以创建一个二维数组的视图作为一维结构化数组,然后使用numpy.unique就这个观点而言.
如果您可以更改阵列的存储约定,或者如果您不介意制作转置数组的副本,这可能对您有用.
这是一个例子:
import numpy as np
# Demo data.
x = np.array([[1,2,3],
[2,0,0],
[1,2,3],
[3,2,2],
[2,0,0],
[2,1,2],
[3,2,1],
[2,0,0]])
# View each row as a structure, with field names 'a', 'b' and 'c'.
dt = np.dtype([('a', x.dtype), ('b', x.dtype), ('c', x.dtype)])
y = x.view(dtype=dt).squeeze()
# Now np.unique can be used. See the `unique` docstring for
# a description of the options. You might not need `idx` or `inv`.
u, idx, inv = np.unique(y, return_index=True, return_inverse=True)
print("Unique vectors")
print(u)
Run Code Online (Sandbox Code Playgroud)