[Reprint] Detailed Numpy.ndarray

Reference link: numpy.ascontiguousarray in Python

Vectors, matrices & multi-dimensional arrays are indispensable tools in numerical calculations; batch processing of array data avoids explicit loop operations on array elements. The result of this is a concise and easier-to-maintain code. And you can use lower-level libraries to implement array operations. Therefore, vectorized calculations are much faster than performing calculations element by element in order. 

In the Python scientific computing environment, the Numpy library provides an efficient data structure for processing arrays, and the core of Numpy is implemented in C language, providing many functions for processing and processing arrays. 

NumPy supports more types of numbers than Python, and there are 5 basic number types: 

Boolean (bool) integer (int) unsigned integer (uint) floating point (float) complex number (complex) 

 

 

 Article Directory

 1. Create a Numpy array 1. np.array is created by np.array() & np.ndarray()

   2. Basic attributes, memory layout data types and other attributes

   3. Numpy native array creation ndarray4, np.arange

  2. Create from existing data 3. Create matrix

 

 

 

The core of the Numpy library is to represent homogeneous multidimensional data-each element occupies the same size block of memory, and all blocks are interpreted in exactly the same way. How to interpret each element in an array is specified by a separate data type object, one of which is associated with each array. In addition to basic types (integer, floating point, etc.), data type objects can also represent data structures.  

 

 

1. Create a Numpy array 

NumPy provides an N-dimensional array type, ndarray, which describes a collection of "items" of the same type. For example, N integers can be used to index items. The items extracted from the array (for example, by index) are represented by Python objects, whose type is one of the array scalar types constructed in NumPy. The array scalar allows easier manipulation of more complex data arrangements. 

 

 The difference between ndarray and array np.array is just a convenient function to create an ndarray, it is not a class itself. The ndarray array is an n-dimensional array object represented by an object of the np.ndarray class, so ndarray is a class object, and array is a method. 

 

There are 5 general mechanisms for creating an array: 

Conversion from other Python structures (for example, lists, tuples) to the creation of numpy native arrays (for example, arange, ones, zeros, etc.) Read the array from disk, whether it is a standard format or a custom format by using strings or buffers Create an array of raw bytes using special library functions (for example, random) 

 

1、np.array 

An ndarray is a (usually a fixed size) multi-dimensional container with items of the same type and size. The size and the number of items in the array are defined by its shape, which is a tuple (tuple) composed of N non-negative integers, used to specify the size of each dimension. The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray. 

Like other container objects in Python, the contents of the ndarray can be accessed and modified by indexing or slicing the array (for example, using N integers) and through the methods and attributes of the ndarray. 

The difference is that ndarrays can share the same data, so changes made in one ndarray may be visible in another. In other words, the ndarray can be the "view" of another ndarray, and the data it refers to is processed by the "base" ndarray. ndarrays can also be views of memory strings owned by Python or objects that implement buffer or array interfaces. 

Created by np.array() & np.ndarray() 

# Create an array.

np.array (object, dtype = None, copy = True, order = 'K', subok = False, ndmin = 0)

 

 

 

np.ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)

 

 

An ndarray is a multi-dimensional container of items of the same type and size. The size and the number of items in the array are defined by its shape, which is a tuple (tuple) composed of N non-negative integers, used to specify the size of each dimension. 

The difference is that ndarrays can share the same data, so changes made in one ndarray may be visible in another. In other words, the ndarray can be the "view" of another ndarray, and the data it refers to is processed by the "base" ndarray. ndarrays can also be views of memory strings owned by Python or objects that implement buffer or array interfaces. 

 

Examples: 

>>> np.array([1, 2, 3])

array([1, 2, 3])

 

>>> np.array([1, 2, 3.0])

array([ 1., 2., 3.])

 

>>> np.array([[1, 2], [3, 4]])

array([[1, 2],

[3, 4]])

 

>>> np.array([1, 2, 3], ndmin=2)

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

 

>>> np.array([1, 2, 3], dtype=complex)

array([ 1.+0.j, 2.+0.j, 3.+0.j])

 

>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])

>>> x['a']

array([1, 3])

 

>>> np.array(np.mat('1 2; 3 4'))

array([[1, 2],

[3, 4]])

 

>>> np.array(np.mat('1 2; 3 4'), subok=True)

matrix([[1, 2],

[3, 4]])

 

 

 

 

>>> np.ndarray(shape=(2,2), dtype=float, order='F')

array([[ -1.13698227e+002, 4.25087011e-303],

[ 2.88528414e-306, 3.27025015e-309]])     #random

 

>>> np.ndarray((2,), buffer=np.array([1,2,3]),

offset=np.int_().itemsize,

dtype=int)                                 # offset = 1 * itemsize, i.e. skip first element

array([2, 3])

 

2. Basic attributes 

Array attributes reflect the inherent information of the array itself. Generally, accessing an array through its properties allows you to get and sometimes set the internal properties of the array without creating a new array. The exposed properties are the core part of the array, and only some properties can be reset meaningfully without creating a new array. Information about each attribute is as follows. 

Memory layout 

The following properties contain information about the memory layout of the array: 

         Method description

| ndarray.flags | Information about the memory layout of the array.                    

| ndarray.shape | A tuple of array dimensions.                            

| ndarray.strides | The byte tuples in each dimension when traversing the array.            

| ndarray.ndim | Array dimension.                                

| ndarray.data | Python buffer object points to the beginning of the data in the array.        

| ndarray.size | The number of elements in the array.                            

| ndarray.itemsize | The length of an array element in bytes.            

| ndarray.nbytes | The total number of bytes consumed by the array elements.                    

| ndarray.base | If the memory comes from other objects, it is the base object.        

 

type of data 

The data type object associated with the array can be found in the dtype attribute: 

         Method | Description

| ndarray.dtype | The data type of the array elements.                        

 

Other attributes 

         Method | Description

| ndarray.T | Transpose the array.                                

| ndarray.real | The real part of the array.                            

| ndarray.imag | The imaginary part of the array.                                

| ndarray.flat | One-dimensional iterator on the array.                        

| ndarray.ctypes | An object that simplifies the interaction between arrays and the ctypes module.        

 

 

3. Numpy native array creates ndarray 

                Method | Description 

| eye(N[, M, k, dtype, order]) | Returns a two-dimensional array, with one on the diagonal and zero elsewhere

| identity(n[, dtype]) | Returns the identity array. 

 

| ones(shape[, dtype, order]) | Returns a new array of the given shape and type, filled with 1

| ones_like(a[, dtype, order, subok, shape]) | Returns an array with the same shape and type as the given array.

| zeros(shape[, dtype, order]) | Returns a new array of the given shape and type, filled with zeros.

| zeros_like(a[, dtype, order, subok, shape]) | Returns an array of zeros with the same shape and type as the given array. 

| full(shape, fill_value[, dtype, order]) | Return a new array of the given shape and type, and fill it with fill_value

| full_like(a, fill_value[, dtype, order, …]) | Return a complete array with the same shape and type as the given array

| empty(shape[, dtype, order]) | Return a new array of the given shape and type without initializing entries

| empty_like(prototype[, dtype, order, subok, …]) | Return a new array with the same shape and type as the given array

 

 

 Functions with _like() such as zeros_like(), ones_like(), empty_like(), etc. create an array with the same shape and type as the parameter array. Frombuffer(), fromstring(), fromfile() and other functions can create arrays from byte sequences or files  

4、np.arange 

| Method | Description 

| arange([start,] stop[, step,][, dtype]) | Returns evenly spaced values ​​within a given interval.

| linspace(start, stop[, num, endpoint, …]) | Returns equal interval numbers in the specified interval.

| logspace(start, stop[, num, endpoint, base, …]) | Return numbers are evenly distributed on a logarithmic scale.  

| geomspace(start, stop[, num, endpoint, …]) | Returns numbers uniformly distributed on a logarithmic scale (geometric progression).       

| meshgrid(*xi, **kwargs) | Returns the coordinate matrix from the coordinate vector. 

| mgridnd_grid | instance, it returns a dense multi-dimensional "meshgrid"

| ogridnd_grid | instance, it returns an open multidimensional "meshgrid"

        

 

2. Create from existing data 

                        Method description

| array(object[, dtype, copy, order, subok, ndmin]) | Create an array

| asarray(a[, dtype, order]) | Convert input to array

| asanyarray(a[, dtype, order]) | Convert input to ndarray, but through ndarray subclass

| ascontiguousarray(a[, dtype]) | Return a contiguous array in memory (ndim >= 1) (C order)

| asmatrix(data[, dtype]) | Interpret the input as a matrix

| copy(a[, order]) | Returns an array copy of the given object

| frombuffer(buffer[, dtype, count, offset]) | Interpret the buffer as a one-dimensional array

| fromfile(file[, dtype, count, sep, offset]) | Construct an array based on the data in the text or binary file

| fromfunction(function, shape, **kwargs) | Construct an array by executing a function on each coordinate

| fromiter(iterable, dtype[, count]) | Create a new one-dimensional array from an iterable object

| fromstring(string[, dtype, count, sep]) | A new one-dimensional array initialized from the text data in the string

| loadtxt(fname[, dtype, comments, delimiter, …]) | Load data from a text file

 

3. Create a matrix 

             Method | Description  

| mat(data[, dtype]) | Interpret the input as a matrix

| bmat(obj[, ldict, gdict]) | Construct matrix objects from strings, nested sequences or arrays

 

| tril(m[, k]) | The lower triangle of the array.                               

| triu(m[, k]) | The upper triangle of the array.                               

| vander(x[, N, increasing]) | Generate Vandermonde Matrix        

 

| diag(v[, k]) | Extract diagonal lines or construct an array of diagonal lines.                 

| diagflat(v[, k]) | Create a two-dimensional array using the flattened input as the diagonal.       

| tri(N[, M, k, dtype]) | An array at and below the given diagonal and zero elsewhere.

Guess you like

Origin blog.csdn.net/u013946150/article/details/113057547