假设我有一个简单的数组:
a = np.arange(3)
以及具有相同长度的索引数组:
I = np.array([0, 0, 1])
我现在要根据索引对值进行分组。 如何对第一个数组的元素进行分组以生成下面的结果
np.array([[0, 1], [2], dtype=object)
以下是我尝试的:
a = np.arange(3)
I = np.array([0, 0, 1])
out = np.empty(2, dtype=object)
out.fill([])
aslists = np.vectorize(lambda x: [x], otypes=['object'])
out[I] += aslists(a)
但是,此方法不会串联列表,而是只保留每个索引的最后一个值:
array([[1], [2]], dtype=object)
或者,对于二维情况:
a = np.random.rand(100)
I = (np.random.random(100) * 5 //1).astype(int)
J = (np.random.random(100) * 5 //1).astype(int)
out = np.empty((5, 5), dtype=object)
out.fill([])
如何根据两个索引数组将项目从a追加到out
1D案例
假设
I
被排序,对于作为输出的数组列表-另一个用
slicing
得到idx
来分裂a
-要获取列表数组作为输出-
样本运行-
2D大小写
对于
2D
填充到2D
数组的情况,我们可以这样做-相关问题 更多 >
编程相关推荐