Bil*_*ing 5 python arrays numpy
我有一个 2D numpy array A。例如:
A = np.array([[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 0]])
Run Code Online (Sandbox Code Playgroud)
我有另一个与B的行相对应的标签数组A。例如:
B = np.array([0, 1, 2, 0, 1])
Run Code Online (Sandbox Code Playgroud)
我想A根据标签分成 3 个数组,所以结果是:
[[[1, 2],
[7, 8]],
[[3, 4],
[9, 0]],
[[5, 6]]]
Run Code Online (Sandbox Code Playgroud)
是否有任何 numpy 内置函数可以实现此目的?
现在,我的解决方案相当丑陋,涉及numpy.where在for循环中重复调用,并对索引元组进行切片以仅包含行。
这是一种方法:
hstack两个数组在一起。sort由arraythe last columnsplit基于价值arrayuniqueindexa = np.hstack((A,B[:,None]))
a = a[a[:, -1].argsort()]
a = np.split(a[:,:-1], np.unique(a[:, -1], return_index=True)[1][1:])
Run Code Online (Sandbox Code Playgroud)
[array([[1, 2],
[7, 8]]),
array([[3, 4],
[9, 0]]),
array([[5, 6]])]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1897 次 |
| 最近记录: |