简体   繁体   中英

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

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)

Normally, we use coordinates like x,y with the horizontal coordinate first and the vertical coordinate second. So numpy makes it convenient to access elements from 2D arrays by giving two coordinates in this order.

However, a 2D array is really an array of arrays; note the definition:

foo = numpy.array([
    [1, 2],
    [3, 4],
    [5, 6]
])

If you ignore the numpy.array constructor, this is a list of lists. The outer list has three elements (each of which is a list), and the value at index 1 is foo[1] == [3, 4] . This makes sense because the matrix is represented as a list of rows , so the index used in the outer list controls the vertical coordinate, ie which row you access.

So, in an expression like foo[1][0] == 3 , the index 1 is the vertical coordinate, and 0 is the horizontal coordinate. That is, it's equivalent to writing foo[x,y] . It's backwards compared to the usual convention, but it follows logically from the fact that a matrix is a list of rows. If the matrix were a list of columns, then foo[x][y] would be correct.

For numpy arrays, this applies just the same for the slice operator. The expression foo[:][1] is equivalent to foo[1,:] , not foo[:,1] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM