from scipy.sparse import coo_matrix
N = a.size
L = a.max()
data = np.ones(N, dtype=int)
sparse_out = coo_matrix((data, (np.arange(N), a.ravel() - 1)), shape=(N, L))
Convert a 2d matrix to a 3d one hot matrix numpy