title: Count unique elements along an axis of a NumPy array
body: <p>I have a three-dimensional array like</p>
  
  <pre>A=np.array([[[1,1],
  [1,0]],
  
  [[1,2],
  [1,0]],
  
  [[1,0],
  [0,0]]])</pre>
  
  <p>Now I would like to obtain an array that has a nonzero value in a given position if only a unique nonzero value (or zero) occurs in that position. It should have zero if only zeros or more than one nonzero value occur in that position. For the example above, I would like</p>
  
  <pre>[[1,0],
  [1,0]]</pre>
  
  <p>since</p>
  
  <ul>
  <li>in <code>A[:,0,0]</code> there are only <code>1</code>s</li>
  <li>in <code>A[:,0,1]</code> there are <code>0</code>, <code>1</code> and <code>2</code>, so more than one nonzero value</li>
  <li>in <code>A[:,1,0]</code> there are <code>0</code> and <code>1</code>, so <code>1</code> is retained</li>
  <li>in <code>A[:,1,1]</code> there are only <code>0</code>s</li>
  </ul>
  
  <p>I can find how many nonzero elements there are with <code>np.count_nonzero(A, axis=0)</code>, but I would like to keep <code>1</code>s or <code>2</code>s even if there are several of them. I looked at <code>np.unique</code> but it doesn't seem to support what I'd like to do.</p>
  
  <p>Ideally, I'd like a function like <code>np.count_unique(A, axis=0)</code> which would return an array in the original shape, e.g. <code>[[1, 3],[2, 1]]</code>, so I could check whether 3 or more occur and then ignore that position.</p>
  
  <hr>
  
  <p>All I could come up with was a list comprehension iterating over the that I'd like to obtain</p>
  
  <pre>[[len(np.unique(A[:, i, j])) for j in range(A.shape[2])] for i in range(A.shape[1])]</pre>
  
  <p>Any other ideas?</p>