NumPy Base--ndarray Object Properties

Source: Internet
Author: User
Tags python list

NumPy is an indispensable third-party library for data analysis using Python, and a lot of scientific computing tools are developed based on NumPy.

The Ndarray object is a multidimensional array that holds the same type of element, is one of the basic objects in NumPy, and the other is a Func object. The main content of this article is:1, Simple introduction Ndarray object ;2, Common properties of Ndarray objects ,3, how to create Ndarray objects ,4, Ndarray element access .
Its dimensions and the number of elements on a dimension are determined by shape. 1 Numpy.ndarray ()

The function in the header is the NumPy constructor, and we can use this function to create a Ndarray object. There are several optional parameters to the constructor:

Parameters type function
Shape int type tuple The shape of a multidimensional array
Dtype Data-type The type of the elements in the array
Buffer Buffer used to initialize the array
Offset Int The offset of the first data in the buffer to initialize the array
Strides int type tuple The subscript of each axis increases by 1 o'clock, the number of bytes added to the data pointer in memory
Order ' C ' or ' F ' ' C ': line priority; ' F ': Column preference

Instance:

>>> Np.ndarray (shape= (2,3), Dtype=int, Buffer=np.array ([1,2,3,4,5,6,7]), offset=0, order= "C") 
Array ([[ 1, 2, 3],
       [4, 5, 6]])
>>> Np.ndarray (shape= (2,3), Dtype=int, Buffer=np.array ([1,2,3,4,5,6,7]), offset =0, order= "F")
Array ([[1, 3, 5],
       [2, 4, 6]])
>>> Np.ndarray (shape= (2,3), Dtype=int, buffer= Np.array ([1,2,3,4,5,6,7]), offset=8, order= "C") 
Array ([[2, 3, 4],
       [5, 6, 7]])
2 Common Properties for Ndarray objects

Next, describe the most commonly used properties of the Ndarray object

Property meaning
T Transpose, same as Self.transpose (), if the dimension is less than 2 returns self
Size Number of elements in an array
ItemSize The byte length of a single element in an array
Dtype The data type object of the array element
Ndim Dimensions of an array
Shape The shape of an array
Data A python buffer object that holds the array data
Flat Returns a one-dimensional iterator of an array
Imag Returns the imaginary part of an array
Real Returns the real part of an array
Nbytes The byte length of all elements in the array

Instance:

>>> A = Np.array (range). Reshape (3,5)
>>> a
array ([[0,  1,  2,  3,  4],
       [5,  6,  7,  8, 9], [A, one,]
       ])
>>> a.t
Array ([[0,  5, 10] ,
       [1,  6, one], [
       2,  7,, [3, 8,]  ,
       [4,  9,]]
>>> a.size
>>> a.itemsize
8
>>> a.ndim
2
>>> a.shape
(3, 5)
>>> a.dtype
dtype (' Int64 ')
3 Creating Ndarray 3.1 Array

Use the array function to create an array from a regular Python list or tuple, and the type of the element is determined by the element type in the original sequence.

Numpy.array (object, Dtype=none, Copy=true, Order=none, Subok=false, ndmin=0)

Instance:

>>> Np.array ([1, 2, 3])
Array ([1, 2, 3])
>>> Np.array ([[1, 2],[3, 4]])
Array ([[1, 2],
       [3, 4]])
>>> C = Array ([[1,2], [3,4]], Dtype=complex)
>>> C
Array ([[1.+0.J, 2.+0.J], 
       [3.+0.J, 4.+ 0.J]]
>>> a = Np.array ([1, 2, 3], ndmin=2)
>>> a
array ([[1, 2, 3]])
>>> A.shape
(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]]

Subok is true and object is a Ndarray subclass (such as a matrix type), the returned array retains the subclass type 3.2 Ones and zeros series functions

At some point, we have determined the dimensions of the array and the length of each dimension before we created the array. We can then use some of the NumPy built-in functions to create the Ndarray.
For example: function ones create an array of all 1, function zeros Create an array of 0, function empty create a random array of content, by default, the types of arrays created with these functions are float64, and if you need to specify a data type, you only need to idle the Dtype parameter:

>>> a = np.ones (Shape = (2, 3))    #可以通过元组指定数组形状
>>> a
array ([[1.,  1.,  1.],
       [ 1.,  1.,  1.]]
>>> a.dtype
dtype (' float64 ')
>>> b = np.zeros (shape = [3, 2], Dtype=np.int64)    # You can also specify an array shape through a list, specifying the array type
>>> b
Array ([[0, 0], [
       0, 0],
       [0, 0]])
>>> B.dtype
dtype (' Int64 ')
>>> C = np.empty ((4,2))
>>> C
Array ([[  0.00000000e+000,   0.00000000e+000],
       [  6.92806325e-310,   6.92806326e-310],
       [  6.92806326e-310,   6.92806326e-310],
       [  0.00000000e+000,   0.00000000e+000]]

The above three functions also have three from a known array, creating a multidimensional array with the same shape: Ones_like, Zeros_like, Empty_like, as follows:

>>> a = [[1,2,3], [3,4,5]]
>>> b = np.zeros_like (a)
>>> b
Array ([[0, 0, 0],< c35/>[0, 0, 0]]
#其他两个函数用法类似

In addition to the several functions used to create arrays, there are several special functions:

The
name of the function Use
Eye Generates a diagonal total of 1, and the rest is all 0 two-dimensional arrays
Identity Generate Unit matrix
Full Generate an array filled with fixed values
Full_like Produces the same array of shapes and given arrays filled with fixed values

In particular, the diagonal position of the full 1 of the eye function has parameter K determination
Usage is as follows:

>>> Np.eye (3, k = 0)    #k = 0 o'clock, all 1 diagonal main diagonal
Array ([[1.,  0.,  0.],
       [0.,  1.,  0.],
       [0.,  0.,  1.]]
>>> Np.eye (3, k = 1)  #k >0, all 1 diagonal moves up the corresponding position
array ([[0.,  1.,  0.],
       [0.,  0.,  1.],
       [0.,  0.,  0.]]
>>> Np.eye (3, k =-1)  #k <0, all 1 diagonal downward moves the corresponding position
array ([[0.,  0.,  0.],
       [1.,  0.,  0.],
       [0.,  1.,  0.]]
>>> np.identity (4)
Array ([[1.,  0.,  0.,  0.],
       [0.,  1.,  0.,  0.],
       [0.,  0.,  1.,  0.],
       [0.,  0.,  0.,  1.]]
>>> np.full (shape = (2,2), Fill_value = 2)
array ([[2.,  2.],
       [2.,  2.]])
>>> Np.full_like ([[[1,2,3],[3,4,5]], 3)
Array ([[3, 3, 3],
       [3, 3, 3]])
3.3 Arange, linspace and LogspaceThe Arange function resembles the range function in Python to create an array linspace function by specifying the initial value, end value, and step length (the default step is 1) to create a one-dimensional arraysThe Logspace function is similar to the linspace, except that it creates a geometric progression, which is also a one-dimensional array
Instance:
>>> Np.arange (0,10,2) 
Array ([0, 2, 4, 6, 8])
>>> np.arange (0,10)
Array ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.linspace (0,10)
Array ([  0.        ,   0.52631579,   1.05263158,   1.57894737,
         2.10526316,   2.63157895,   3.15789474,   3.68421053,
         4.21052632,   4.73684211,   5.26315789,   5.78947368,
         6.31578947,   6.84210526,   7.36842105,   7.89473684,
         8.42105263,   8.94736842,   9.47368421  .        ]
>>> np.logspace (0, a)
array ([  1.00000000e+00,   1.29154967e+01,   1.66810054e+02,
         2.15443469e+03,   2.78255940e+04,   3.59381366e+05,
         4.64158883e+06,   5.99484250e+07,   7.74263683e+08,
         1.00000000e+10])
3.4 fromstring and FromFunctionThe FromString function reads data from a string and creates an array fromfunction function that is the first argument used as a function for each array element (either a function object or a lambda expression), and the second argument is the shape of an array
Instance:
>>> S1 = "1,2,3,4,5" >>> np.fromstring (S1, Dtype=np.int64, sep= ",") array ([1, 2, 3, 4, 5]) >>> S2 = "1.01 2.23 3.53 4.76" >>> np.fromstring (S2, Dtype=np.float64, sep= "") array ([1.01, 2.23, 3.53, 4.76]) &   Gt;>> def func (i, J): ... return (i+1) * (j+1) >>> np.fromfunction (func, (9,9)) Array ([[1., 2.,   3., 4., 5., 6., 7., 8., 9., 2., 4, 6., 8, 10., 12.14.], [16., 6., 9., 12., 15., 18., 21., 24., 27.], [4., 8., 12., 16., 20., 24, 28., 32., 36.], [5.   , 10., 15., 20., 25., 30., 35, 40., 45.], [6., 12., 18., 24., 30, 36., 42., 48., 54.], [
       7., 14., 21., 28., 35., 42., 49., 56., 63.], [8., 16., 24., 32., 40, 48., 56., 64., 72;
[9., 18., 27., 36., 45., 54., 63., 72., 81.]]
  >>> np.fromfunction (Lambda i,j:i+j, (3,3), dtype = int) array ([[0, 1, 2],     [1, 2, 3], [2, 3, 4]] 

In addition to the above two functions there are several other similar to get data from the outside and create Ndarray, such as: Frombuffer, FromFile, Fromiter, have not been used, etc. in the detailed record 4 Ndarray to create a special two-dimensional array

Ndarray provides some special functions for creating two-dimensional arrays. The matrix in NumPy is a subclass of the encapsulated two-dimensional array ndarray. The creation of two-dimensional arrays, as described here, is still returned as a Ndarray object, not as a matrix subclass. For the creation and operation of the Matrix, the following notes are described in detail. For ease of expression, the following matrix is used to represent the created two-dimensional array.
1. The Diag function returns the diagonal element of a matrix, or creates a diagonal array, which is controlled by the parameter K
2. The Diagflat function takes the input as the diagonal element, creates a matrix, and the diagonal is controlled by the parameter K
3. The tri function generates a matrix in which the following elements are all 1, the rest is 0, and the diagonal is controlled by the parameter K
4. The Tril function enters a matrix, returns the lower triangular matrix of the matrix, and the boundary diagonal of the lower triangle is controlled by the parameter K
5. The Triu function is similar to the Tril and returns the upper triangular matrix of the matrix.
6. The Vander function enters a one-dimensional array, returning a Vandermonde matrix

#diag用法 >>> x = Np.arange (9). Reshape ((3,3)) >>> x Array ([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> Np.diag (x) array ([0, 4, 8]) >>> np.diag (x, k=1) array ([1, 5]) >>> np.diag (x, K=-1) Array ([ 3, 7]) >>> Np.diag (Np.diag (x)) array ([[0, 0, 0], [0, 4, 0], [0, 0, 8]]) >>> Np.diag (Np.dia g (x), k=1) array ([[0, 0, 0, 0], [0, 0, 4, 0], [0, 0, 0, 8], [0, 0, 0, 0]]) #diagflat用法 >>> n P.diagflat ([[[1,2],[3,4]]) array ([[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) >>&gt ; Np.diagflat ([1,2,3], K=-1) array ([[0, 0, 0, 0], [1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0]]) #tri >& Gt;> Np.tri (3,4, k=1, Dtype=int) Array ([[1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]) >>> Np.tri ( 3,4) Array ([[1., 0., 0., 0.], [1., 1., 0., 0.], [1., 1., 1., 0.]] #tril与triu >>> x = n P.arange (Reshape) (3,4) >>> x Array ([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, one]]) >>> Np.tril (x, K   =1) Array ([[0, 1, 0, 0], [4, 5, 6, 0], [8, 9,]]) >>> Np.triu (x, k=1) array ([[0,   1, 2, 3], [0, 0, 6, 7], [0, 0, 0, one]]) #vander >>> np.vander ([2,3,4,5]) Array ([[8, 4, 2, 1], [M, 9, 3, 1], [4, 1], [MB, 5, 1]] >>> Np.vand ER ([2,3,4,5], n=3) Array ([[4, 2, 1], [9, 3, 1], [16, 4, 1], [25, 5, 1]]
5 Ndarray element Access 5.1 One-dimensional array

For one-dimensional Ndarray, you can access the built-in list using Python: integer indexes, slices, iterations, and so on
about Ndarray slices
Similar to the built-in list slice, in the form of:
Array[beg:end:slice]
Beg: Start index
End: Ending index (does not contain this element)
Step: Interval
It is to be noted that:
1. Beg can be empty, indicating starting from index 0;
2. End can also be empty, indicating that an index is reached (including the last element);
3. Step is empty, indicating interval of 1;
4. Negative index: The index of the penultimate element is-1, minus 1
5. Negative step: Get the element from the back forward

>>> x = Np.arange *4
>>> x
Array ([0,  4,  8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 5 2, x[11])
>>>
>>> x[4:9] Array ([A, K, M
])
>>> x[ : 10:3]
Array ([0, A, m])
>>> x[0:13:2]
Array ([0, 8, K, K, K  ])
>> > x[::-1] #逆置数组 Array ([k,, 8, K, K, K, M,
4,  0])-
> >> Print [Val for Val in X]    #迭代元素
[0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60]

Notably, the elements in the array returned by the Ndarray are the index of the original array element, and modifying the returned array element affects the value of the original array

>>> x[:-1]
Array ([0, 5, A, M, A, M]  )
>>> y = x[::-1]
>>> y
  
   array ([A,  5,  0])
>>> y[0] =    #修改y的首个元素的值
>>> Y
   array ([A,  5,   0])
>> in the same. > x      #x [1] is also modified (essentially an element)
array ([  0,   5, A,  30,  40, 100])
  

In addition to the previous way of accessing elements similar to the list, Ndarray has a list that specifies the index to get the elements from the Ndarray, for example:

>>> x = Np.arange (a) *5
>>> x
Array ([0,  5, A, a, A, m)
>> ;> x[[0, 2, 4, 5, 9]]    #指定获取索引为0, 2, 4, 5, 9 elements
Array ([0, 10, 20, 25, 45])
5.2 Multi-dimensional arrays

In multidimensional Ndarray, each dimension is called an axis axis. Axis axis is very important in Ndarray, and many operations on Ndarray objects are based on axis, such as sum, mean, and so on, there will be an axis parameter (for some operations on this axis axis), which will be described in detail later.
For multidimensional arrays, because each axis has an index, the indexes are split by commas, for example:

>>> x = Np.arange (0, 5). Reshape (4, 5) >>> x Array ([[0, 5, 10, 15, 20], [x[1,2], [3, M, (), [)] >>>] #第1行, 2nd of the same list, in all of the same. 5 >>> X[1:4, 3] #第1行到第3行中所有第 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.