3

I want to know more numpy to process array. I find that it is different between a[:,None] and a[:,]. I want to dig into where and when to use them.

I try to slove the problem that subtract 1d from 2d array in special way just like numpy-subtract-add-1d-array-from-2d-array where I realise it's different between a[:,None] and a[:,].


>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])

>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> b = np.array([1,2,3])

>>> b
array([1, 2, 3])

>>> b[:,None]
array([[1],
       [2],
       [3]])

>>> b[:,]
array([1, 2, 3])

>>> b[None,:]
array([[1, 2, 3]])

>>> a-b[None,:]
array([[0, 0, 0],
       [3, 3, 3],
       [6, 6, 6]])

>>> b[,:] #false operation!!!
SyntaxError: invalid syntax

>>> a-b
array([[0, 0, 0],
       [3, 3, 3],
       [6, 6, 6]])

>>> a-b[:,np.newaxis]
array([[0, 1, 2],
       [2, 3, 4],
       [4, 5, 6]])

Can anyone give me official or specific reference about it? I will really appreciate you!

haofeng
  • 592
  • 1
  • 5
  • 21
  • `a[:]` does nothing except return a view of `a`; no change in dimensions (check it). The trailing `,` in a[:,]` just makes the indexing argument a tuple (that's a basic Python operation), which functionally is the same, a plain view. `a[,:]` is a syntax error. That's raised by interpreter; that's not a `numpy` issue. – hpaulj Apr 05 '19 at 15:58
  • Thank for your recommendation! I has already checked it. You are right, but it does is numpy issue, becasue python 3.x does not support tuple as list indices. – haofeng Apr 06 '19 at 01:45
  • Syntax errors are raised by the Python interpreter. `[1,2,3][:,]` raises a TypeError, `x[,:]` or `x[,3]` raises a syntax error, regardless of what `x` is. I think the relevant syntax specification is `target_list` in https://docs.python.org/3/reference/simple_stmts.html#assignment-statements. Even outside of indexing `(,2)` and `[,34]` are wrong. – hpaulj Apr 06 '19 at 02:04
  • Ahhh! You hit the nail! Yeah! – haofeng Apr 06 '19 at 02:27

1 Answers1

2

I guess instead of None you should use np.newaxis, which is actually the same, but with np.newaxis the code is more readable, as it inserts a new axis at this dimension.

See: https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#numpy.newaxis

Slayer
  • 832
  • 1
  • 6
  • 21
Magellan88
  • 2,543
  • 3
  • 24
  • 36