python - 如何使用 numpy 有效地按值展开矩阵?

标签 python arrays numpy

我有一个矩阵 M,其中的值从 0 到 N。我想展开这个矩阵以创建一个新矩阵 A,其中每个子矩阵 A[i, :, :] 代表是否 M == i。

下面的解决方案使用了一个循环。

# Example Setup
import numpy as np

np.random.seed(0)
N = 5
M = np.random.randint(0, N, size=(5,5))

# Solution with Loop
A = np.zeros((N, M.shape[0], M.shape[1]))
for i in range(N):
    A[i, :, :] = M == i

这产生:

M
array([[4, 0, 3, 3, 3],
       [1, 3, 2, 4, 0],
       [0, 4, 2, 1, 0],
       [1, 1, 0, 1, 4],
       [3, 0, 3, 0, 2]])

M.shape
# (5, 5)


A 
array([[[0, 1, 0, 0, 0],
        [0, 0, 0, 0, 1],
        [1, 0, 0, 0, 1],
        [0, 0, 1, 0, 0],
        [0, 1, 0, 1, 0]],
       ...
       [[1, 0, 0, 0, 0],
        [0, 0, 0, 1, 0],
        [0, 1, 0, 0, 0],
        [0, 0, 0, 0, 1],
        [0, 0, 0, 0, 0]]])

A.shape
# (5, 5, 5)

有没有更快的方法,或者在单个 numpy 操作中完成它的方法?

最佳答案

广播比较是你的 friend :

B = (M[None, :] == np.arange(N)[:, None, None]).view(np.int8)

 np.array_equal(A, B)
# True

这个想法是以这样一种方式扩展维度,以便可以以所需的方式广播比较。


正如@Alex Riley 在评论中指出的那样,您可以使用 np.equal.outer 来避免自己做索引工作,

B = np.equal.outer(np.arange(N), M).view(np.int8)

np.array_equal(A, B)
# True

关于python - 如何使用 numpy 有效地按值展开矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55543949/

相关文章:

python - 将 Pandas 时间戳插入 Mongodb

python - python中类似生产者/消费者的多线程

python - 使用 PySerial 读取空字节

ios - Swift 2 .plist dictArray 到远程 Json 数组错误

python - 迭代 ndarray

python - 在管理界面显示用户组?

java - Java 中的对象数组有默认值吗?

Java 游戏开发 : Sprite sheet frame by row and column?

python - scikit-learn 中的 hmmlearn 中缺少数据

python - Python 中拉格朗日乘数的 Numpy arange 错误