pittnerf
pittnerf

Reputation: 801

What is the difference in NumPy between [:][:] and [:,:]?

I am quite familiar with python programming but I found some strange cases where the following two lines of code provided different results (assuming that the two arrays are 2-dimensional):

A[:][:] = B[:][:]

and

A[:,:] = B[:,:]

I am wondering if there is any case, explication.

Any hint?

Example :

>>> x = numpy.array([[1, 2], [3, 4], [5, 6]])
>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> x[1][1]
4                 # expected behavior
>>> x[1,1]
4                 # expected behavior
>>> x[:][1]
array([3, 4])     # huh?
>>> x[:,1]
array([2, 4, 6])  # expected behavior

Upvotes: 1

Views: 190

Answers (1)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27281

Let's take a step back. Try this:

>>> x = np.arange(6)

>>> x
array([0, 1, 2, 3, 4, 5])

>>> x[:]
array([0, 1, 2, 3, 4, 5])

>>> x[:][:]
array([0, 1, 2, 3, 4, 5])

>>> x[:][:][:][:][:][:][:][:][:][:]
array([0, 1, 2, 3, 4, 5])

It looks like x[:] is equal to x. (Indeed, x[:] creates a copy of x.)

Therefore, x[:][1] == x[1].


Is this consistent with what we should expect? Why should x[:] be a copy of x? If you're familiar with slicing, these examples should clarify:

>>> x[0:4]
array([0, 1, 2, 3])

>>> x[0:6]
array([0, 1, 2, 3, 4, 5])

>>> x[0:]
array([0, 1, 2, 3, 4, 5])

>>> x[:]
array([0, 1, 2, 3, 4, 5])

We can omit the 0 and 6 and numpy will figure out what the maximum dimensions are for us.


Regarding the first part of your question, to create a copy of B, you can do any of the following:

A = B[:, :]
A = B[...]
A = np.copy(B)

Upvotes: 1

Related Questions