NumPy foundation entry profile manipulation and copying, view

Keywords: Python

1. Change array shape

The shape of an array is determined by the number of elements along each axis, and can be changed using various commands. Note that the following three commands return the modified array without changing the original array:

import numpy as np
a = np.floor(10*np.random.random((3,4)))
print (a)
print (a.shape)
print (a.ravel())  # Decomposing an array into a one-dimensional array
print (a.reshape(6,2))  # Change array structure
print (a.T)  # Reverse the number of rows and columns of an array
print (a.T.shape)
print (a.shape)

In the example above, the reshape function returns its parameters with the modified shape, while there is another method, ndarray.resize, which modifies the array itself to change the shape of the array.

2. Different arrays stacked together

Several arrays can be stacked along different axes:

import numpy as np
a = np.floor(10*np.random.random((2,2)))
print (a)
b = np.floor(10*np.random.random((2,2)))
print (b)
print (np.vstack((a,b)))  # Stack vertically
print (np.hstack((a,b)))  # Stack horizontally
print (np.column_stack((a,b)))  # Stack horizontally
import numpy as np
from numpy import newaxis
a = np.array([4.,2.])
b = np.array([3.,8.])
print (np.column_stack((a,b)))  # returns a 2D array
print (np.hstack((a,b)))  # the result is different
print (a[:,newaxis])  # this allows to have a 2D columns vector
print (np.column_stack((a[:,newaxis],b[:,newaxis])))
print (np.hstack((a[:,newaxis],b[:,newaxis])))  # the result is the same

In addition, the row? Stack function is equivalent to vstack in any input array. In fact, row'stack is the alias of vstack. Attention at the same time
In complex cases, r and c are useful for creating arrays by stacking numbers along an axis. They allow range text (':')

3. Split an array into several smaller arrays

With hsplit, you can split an array along its horizontal axis by specifying the number of arrays of the same shape to be returned, or by specifying the columns to be divided after. vsplit splits along a vertical axis, and array? Split allows you to specify which axis to split along.

import numpy as np
a = np.floor(10*np.random.random((2,12)))
print (a)
print (np.hsplit(a,3))  # Split a into 3
print (np.hsplit(a,(3,4)))  # Split a after the third and the fourth column

4. copy

When you manipulate and manipulate an array, sometimes you copy its data to a new array, sometimes not. For beginners, this usually causes confusion. There are three situations:

1. There is no copy at all (simple allocation does not copy array objects or their data), and Python passes variable objects as references, so function calls do not copy.

import numpy as np
def f(x):
a = np.arange(12)
b = a  # no new object is created
print (b is a)  # a and b are two names for the same ndarray object
b.shape = 3,4  # changes the shape of a
print (a.shape)
print (id(a))  # id is a unique identifier of an object
print (f(a))

2. View or shallow copy (different array objects can share the same data. The view method creates a new array object that views the same data. Slice array returns its view.)

import numpy as np
a = np.arange(12)
c = a.view()
print (c is a)
print (c.base is a)  # c is a view of the data owned by a
print (c.flags.owndata)
c.shape = 2,6                      # a's shape doesn't change
print (a.shape)
c[0,4] = 1234                      # a's data changes
print (a)
s = a[ : , 1:3]     # spaces added for clarity; could also be written "s = a[:,1:3]"
s[:] = 10           # s[:] is a view of s. Note the difference between s=10 and s[:]=10
print (a)

3. Deep copy (the copy method copies the array and its data completely. Sometimes copy should be called if the original array slice is no longer needed.

import numpy as np
a = np.arange(12)
d = a.copy()  # a new array object with new data is created
print (d is a)
print (d.base is a)  # d doesn't share anything with a
d[0,0] = 9999
print (a)

Overview of functions and methods

This is a list of useful NumPy function and method names sorted by category. For a complete list, see routine.

Array creation
arange, array, copy, empty, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones, ones_like, r_, zeros, zeros_like

Conversion times
ndarray.astype, atleast_1d, atleast_2d, atleast_3d, mat

Operation mode
array_split, column_stack, concatenate, diagonal, dsplit, dstack, hsplit, hstack, ndarray.item, newaxis, ravel, repeat, reshape, resize, squeeze, swapaxes, take, transpose, vsplit, vstack

all, any, nonzero, where

argmax, argmin, argsort, max, min, ptp, searchsorted, sort

Mode of operation
choose, compress, cumprod, cumsum, inner, ndarray.fill, imag, prod, put, putmask, real, sum

Basic statistics
cov, mean, std, var

Basic linear algebra
cross, dot, outer, linalg.svd, vdot

Published 4 original articles, won praise 7, visited 1191
Private letter follow

Posted by topflight on Fri, 10 Jan 2020 08:25:46 -0800