首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >矩阵python的向量(positionx,positionx,value)

问矩阵python的向量(positionx,positionx,value)
EN

Stack Overflow用户
提问于 2013-11-17 05:35:58
回答 3查看 87关注 0票数 2

我有一个值的矩阵,我想要一个包含矩阵和值的位置的向量。

第一个想法:双桶存储索引和值

第二个想法:创建一个包含序列的ndarray

有没有其他最有效的想法?

对不起,我的英语不好。

输入(图1C):

代码语言:javascript
复制
[[0 1 2 3 4 5]
 [6 7 8 9 10 11]]

输出:

代码语言:javascript
复制
[[0 0 1][0 1 2] [0 2 3] [0 3 4] [0 4 5] [1 0 6] [1 1 7] [1 2 8] [1 3 9] [1 4 10] [1 5 11] ... ]

感谢你们所有人的回答,你们帮助解决了这个问题并理解了numpy。

EN

回答 3

Stack Overflow用户

发布于 2013-11-17 07:07:50

这里有一种非常简洁的方法:

代码语言:javascript
复制
import numpy as np
arr = np.random.random((2, 6))
x, y = np.indices(arr.shape)
output = np.column_stack([x.ravel(), y.ravel(), arr.ravel()])

这里有一个非常可爱的方法,可以最大限度地减少内存使用:

代码语言:javascript
复制
import numpy as np
arr = np.random.random((2, 6))
output = np.indices(arr.shape + (1,), dtype=arr.dtype)
output[-1, ..., 0] = arr
output = output.reshape(arr.ndim + 1, -1).T
票数 2
EN

Stack Overflow用户

发布于 2013-11-17 06:01:31

代码语言:javascript
复制
import numpy as np

mat = np.arange(12).reshape(2,6)

result = np.c_[(np.array(list(np.ndindex(mat.shape))), mat.ravel())]
print(result)

收益率

代码语言:javascript
复制
[[ 0  0  0]
 [ 0  1  1]
 [ 0  2  2]
 [ 0  3  3]
 [ 0  4  4]
 [ 0  5  5]
 [ 1  0  6]
 [ 1  1  7]
 [ 1  2  8]
 [ 1  3  9]
 [ 1  4 10]
 [ 1  5 11]]

注意:像在np.array(list(np.ndindex(mat.shape)))中一样使用list会形成一个临时的Python列表。这很方便,但内存效率不是很高,因为Python列表比“等效的”NumPy数组大得多。您可以通过使用np.fromiter来避免使用临时Python列表;例如,(与shx2's ndenumerate idea结合使用):

代码语言:javascript
复制
import numpy as np
arr = np.arange(12).reshape(2,6)

def ndindex_values(arr):
    for idx, value in np.ndenumerate(arr):
        for coord in idx:
            yield coord
        yield value

result = np.fromiter(
    ndindex_values(arr),
    count=arr.size*(len(arr.shape)+1),
    dtype=arr.dtype).reshape(arr.size, -1)
票数 1
EN

Stack Overflow用户

发布于 2013-11-17 06:01:35

使用numpy.ndenumerate。

代码语言:javascript
复制
list(np.ndenumerate(a))
=>
[((0, 0), 0),
 ((0, 1), 1),
 ((0, 2), 2),
 ((0, 3), 3),
 ((0, 4), 4),
 ((0, 5), 5),
 ((1, 0), 6),
 ((1, 1), 7),
 ((1, 2), 8),
 ((1, 3), 9),
 ((1, 4), 10),
 ((1, 5), 11)]

要获得问题中指定的输出,即展平索引和值,您可以执行以下操作:

代码语言:javascript
复制
[ list(idx) + [value] for idx, value in np.ndenumerate(a) ]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20024214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档