title: Subtract Mean from Multidimensional Numpy-Array
body: <p>I'm currently learning about broadcasting in Numpy and in the book I'm reading (<a href="https://www.oreilly.com/library/view/python-for-data/9781491957653/" rel="nofollow noreferrer">Python for Data Analysis by Wes McKinney</a> the author has mentioned the following example to "demean" a two-dimensional array:</p>
  
  <pre class="lang-py prettyprint-override"><code>import numpy as np
  
  arr = np.random.randn(4, 3)
  print(arr.mean(0))
  demeaned = arr - arr.mean(0)
  print(demeaned)
  print(demeand.mean(0))
  </code></pre>
  
  <p>Which effectively causes the array <code>demeaned</code> to have a mean of 0.</p>
  
  <p>I had the idea to apply this to an image-like, three-dimensional array:</p>
  
  <pre class="lang-py prettyprint-override"><code>import numpy as np
  
  arr = np.random.randint(0, 256, (400,400,3))
  demeaned = arr - arr.mean(2)
  </code></pre>
  
  <p>Which of course failed, because according to the broadcasting rule, the trailing dimensions have to match, and that's not the case here:</p>
  
  <pre class="lang-py prettyprint-override"><code>print(arr.shape)  # (400, 400, 3)
  print(arr.mean(2).shape)  # (400, 400)
  </code></pre>
  
  <p>Now, i have gotten it to work mostly, by substracting the mean from every single index in the third dimension of the array:</p>
  
  <pre class="lang-py prettyprint-override"><code>demeaned = np.ones(arr.shape)
  
  for i in range(3):
      demeaned[...,i] = arr[...,i] - means
  
  print(demeaned.mean(0))
  </code></pre>
  
  <p>At this point, the returned values are very close to zero and i think, that's a precision error. Am i actually right with this thought or is there another caveat, that i missed?</p>
  
  <p>Also, this doesn't seam to be the cleanest, most '<code>numpy</code>'-way to achieve what i wanted to achieve. Is there a function or a principle that i can make use of to improve the code?</p>