我有一个值的矩阵,我想要一个包含矩阵和值的位置的向量。
第一个想法:双桶存储索引和值
第二个想法:创建一个包含序列的ndarray
有没有其他最有效的想法?
对不起,我的英语不好。
输入(图1C):
[[0 1 2 3 4 5]
[6 7 8 9 10 11]]输出:
[[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。
发布于 2013-11-17 07:07:50
这里有一种非常简洁的方法:
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()])这里有一个非常可爱的方法,可以最大限度地减少内存使用:
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发布于 2013-11-17 06:01:31
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)收益率
[[ 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结合使用):
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)发布于 2013-11-17 06:01:35
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)]要获得问题中指定的输出,即展平索引和值,您可以执行以下操作:
[ list(idx) + [value] for idx, value in np.ndenumerate(a) ]https://stackoverflow.com/questions/20024214
复制相似问题