将numpy数组重新映射到字典
我想根据字典重新映射numpy数组。 假设有一个numpy数组,有N行3列。现在我想根据它的索引重新映射这些值,这些索引是以元组形式写入字典的。 这很好:将numpy数组重新映射到字典,numpy,dictionary,reshape,remap,Numpy,Dictionary,Reshape,Remap,我想根据字典重新映射numpy数组。 假设有一个numpy数组,有N行3列。现在我想根据它的索引重新映射这些值,这些索引是以元组形式写入字典的。 这很好: import numpy as np a = np.arange(6).reshape(2,3) b = np.zeros(6).reshape(2,3) print a print A dictt = { (0,0):(0,2), (0,1):(0,1), (0,2):(0,0), (1,0):(1,2), (1,1):(1,1), (
import numpy as np
a = np.arange(6).reshape(2,3)
b = np.zeros(6).reshape(2,3)
print a
print A
dictt = { (0,0):(0,2), (0,1):(0,1), (0,2):(0,0), (1,0):(1,2), (1,1):(1,1), (1,2):(1,0) }
for key in dictt:
b[key] = a[dictt[key]]
print b
a = [[0 1 2]
[3 4 5]]
b = [[ 2. 1. 0.]
[ 5. 4. 3.]]
假设有N行,其中N是偶数。现在,我想将相同的映射(在上面的示例中对这两行有效)应用到所有其他行。
因此,我希望从以下位置获得一个数组:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
致:
有什么想法吗?由于每个数组中有192000个条目需要重新映射,因此我希望能够快速完成此操作。为了简单起见,我只使用[:-1]
a = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
b = [item[::-1] for item in a]
>>> b
[[2, 1, 0], [5, 4, 3], [8, 7, 6]]
在python2或python3中?那么字典中定义的顺序是任意的?还是您总是想镜像您的数据?因为如果不使用字典,会有更有效的方法。。。(numpy.fliplr)谢谢你的建议。它是Python2.7。不幸的是,顺序是随机的,没有镜像。如上所述:因为a是numpy数组,所以b=np。fliplr(a)应该是最有效的方法。我没有检查它的效率,你可能是对的。
a = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
b = [item[::-1] for item in a]
>>> b
[[2, 1, 0], [5, 4, 3], [8, 7, 6]]