原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12245002.html

 

Basic Indexing and Slicing

One-dimensional arrays are simple; on the surface they act similarly to Python lists:

NumPy array basic indexing and slicing

Note: As you can see, if you assign a scalar value to a slice, as in arr[5:8] = 12, the value is propagated (or broadcasted henceforth) to the entire selection. An important first distinction from Python’s built-in lists is that array slices are views on the original array. This means that the data is not copied, and any modifications to the view will be reflected in the source array. As NumPy has been designed to be able to work with very large arrays, you could imagine performance and memory problems if NumPy insisted on always copying data.

 

The “bare” slice [:] will assign to all values in an array:

NumPy array basic indexing and slicing

 

If you want a copy of a slice of an ndarray instead of a view, you will need to explicitly copy the array—for example, arr[5:8].copy().

NumPy array basic indexing and slicing

 

In a two-dimensional array, the elements at each index are no longer scalars but rather one-dimensional arrays. Thus, individual elements can be accessed recursively. But that is a bit too much work, so you can pass a comma-separated list of indices to select individual elements.

NumPy array basic indexing and slicing

 

Indexing elements in a NumPy array

NumPy array basic indexing and slicing

AXIS 0 IS THE DIRECTION ALONG THE ROWS

NumPy array basic indexing and slicing 

AXIS 1 IS THE DIRECTION ALONG THE COLUMNS

NumPy array basic indexing and slicing

 

In multidimensional arrays, if you omit later indices, the returned object will be a lower dimensional ndarray consisting of all the data along the higher dimensions. So in the 2 × 2 × 3 array arr3d: 

NumPy array basic indexing and slicing

 

Similarly, arr3d[1, 1] gives you all of the values whose indices start with (1, 1), forming a 1-dimensional array:

NumPy array basic indexing and slicing

 

Indexing with slices

One-dimensional array slicing

Like one-dimensional objects such as Python lists, ndarrays can be sliced with the familiar syntax:

NumPy array basic indexing and slicing

Two-dimensional array slicing

NumPy array basic indexing and slicing

NumPy array basic indexing and slicing 

Reference

Python for Data Analysis Second Edition

https://www.sharpsightlabs.com/blog/numpy-axes-explained/

相关文章: