二维 numpy 数组列中的唯一条目

亚历山大·海斯

我有一个整数数组:

import numpy as np

demo = np.array([[1, 2, 3],
                 [1, 5, 3],
                 [4, 5, 6],
                 [7, 8, 9],
                 [4, 2, 3],
                 [4, 2, 12],
                 [10, 11, 13]])

而且我想要列中的唯一值数组,如有必要,填充一些内容(例如 nan):

[[1, 4, 7, 10, nan],
 [2, 5, 8, 11, nan],
 [3, 6, 9, 12,  13]]

当我遍历转置数组并使用上一个问题解决方案时,确实有效但我希望会有一个内置的方法:boolean_indexing

solution = []
for row in np.unique(demo.T, axis=1):
    solution.append(np.unique(row))

def boolean_indexing(v, fillval=np.nan):
    lens = np.array([len(item) for item in v])
    mask = lens[:,None] > np.arange(lens.max())
    out = np.full(mask.shape,fillval)
    out[mask] = np.concatenate(v)
    return out

print(boolean_indexing(solution))
杰罗姆·理查德

AFAIK,没有内置的解决方案。话虽如此,您的解决方案对我来说似乎有点复杂。您可以创建一个带有初始化值的数组,并用一个简单的循环填充它(因为您已经使用了循环)。

solution = [np.unique(row) for row in np.unique(demo.T, axis=1)]

result = np.full((len(solution), max(map(len, solution))), np.nan)
for i,arr in enumerate(solution):
    result[i][:len(arr)] = arr

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章