numpy的数组索引和更换 [英] NumPy Array Indexing and Replacing
本文介绍了numpy的数组索引和更换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个3D numpy的数组如下:
(3L,5L,5L)
如果在三维位置的一个元素,例如, [150,160,170]
存在。我怎么能转换他们都到 [0,0,0]
?
导入numpy的是NP
A = np.ones((3,5,5))
一个[0,2:4,2:4] = 150
一个[0,0:1,0:1] = 150 #important!
一个[1,2:4,2:4] = 160
一个[2,2:4,2:4] = 170
打印一
预期的结果应该是:
[[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 0 0 1]
[1 1 0 0 1]
[1 1 1 1 1] [1 1 1 1 1]
[1 1 1 1 1]
[1 1 0 0 1]
[1 1 0 0 1]
[1 1 1 1 1] [1 1 1 1 1]
[1 1 1 1 1]
[1 1 0 0 1]
[1 1 0 0 1]
[1. 1. 1. 1. 1.]]]
解决方案
首先,我会转换成三倍的堆栈:
B = np.reshape(a.transpose(2,1,0),[25.3])
然后找到你想要的值:
IDX = np.where((B == np.array([150,160,170]))。所有(轴= 1))
和你想要的任何值替换:
B [IDX] = 0
和最后转换回原始形状
C = np.reshape(B,[5,5,3])。移调(2,1,0)
I have a 3d numpy array as follows:
(3L, 5L, 5L)
If one element in 3d positions, for instance, [150, 160, 170]
exists. How can I convert all of them into [0,0,0]
?
import numpy as np
a = np.ones((3,5,5))
a[0,2:4,2:4] = 150
a[0,0:1,0:1] = 150 #important!
a[1,2:4,2:4] = 160
a[2,2:4,2:4] = 170
print a
The expected result should be:
[[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 1. 1. 1.]]
[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 1. 1. 1.]]
[[ 1. 1. 1. 1. 1.]
[ 1. 1. 1. 1. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 0. 0. 1.]
[ 1. 1. 1. 1. 1.]]]
解决方案
First I would convert into a stack of triples:
b = np.reshape(a.transpose(2, 1, 0), [25,3])
Then find the values you want:
idx = np.where((b == np.array([150, 160, 170])).all(axis=1))
And replace with whatever value you want:
b[idx] = 0
And finally convert back to the original shape:
c = np.reshape(b, [5, 5, 3]).transpose(2, 1, 0)
这篇关于numpy的数组索引和更换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文