Hi Folks,
I have array (numpy.ndarray object) with non-zero elements cumulated 'somewhere' (like a array([[0,0,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]])) and I need sub-array with just non-zero elements (array([[1,1],[0,1]])). I can do this with iterating throught an array, but I also found some magic tricks with boolen operators in indexing and nonzero function, but it is still not clear to me, how to use it.
I am sure that this will be pretty easy for those who are familiar with this kind of array indexing and I hope I will be one of them soon :-).
Thanks a lot Radek
Fri, 10 Sep 2010 11:46:47 +0200, Radek Machulka wrote:
I have array (numpy.ndarray object) with non-zero elements cumulated 'somewhere' (like a array([[0,0,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]])) and I need sub-array with just non-zero elements (array([[1,1],[0,1]])). I can do this with iterating throught an array, but I also found some magic tricks with boolen operators in indexing and nonzero function, but it is still not clear to me, how to use it.
x = np.array([[0,0,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]]) i, j = x.any(0).nonzero()[0], x.any(1).nonzero()[0] x[i[:,None], j[None,:]]
array([[1, 1], [0, 1]])
Thanks, but...
x = array([[0,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,0,0]]) x
array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 0]])
i, j = x.any(0).nonzero()[0], x.any(1).nonzero()[0] x[i[:,None], j[None,:]]
array([[1, 0], [0, 1], [0, 0]])
R.
2010/9/10, Pauli Virtanen pav@iki.fi:
Fri, 10 Sep 2010 11:46:47 +0200, Radek Machulka wrote:
I have array (numpy.ndarray object) with non-zero elements cumulated 'somewhere' (like a array([[0,0,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]])) and I need sub-array with just non-zero elements (array([[1,1],[0,1]])). I can do this with iterating throught an array, but I also found some magic tricks with boolen operators in indexing and nonzero function, but it is still not clear to me, how to use it.
x = np.array([[0,0,0,0],[0,1,1,0],[0,0,1,0],[0,0,0,0]]) i, j = x.any(0).nonzero()[0], x.any(1).nonzero()[0] x[i[:,None], j[None,:]]
array([[1, 1], [0, 1]])
NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion
Fri, 10 Sep 2010 14:35:46 +0200, Radek Machulka wrote:
Thanks, but...
x = array([[0,0,0,0],[0,1,0,0],[0,0,1,1],[0,0,0,0]]) x
array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 0]])
i, j = x.any(0).nonzero()[0], x.any(1).nonzero()[0]
Should be
j, i = x.any(0).nonzero()[0], x.any(1).nonzero()[0]