Python Numpy array initialization and basic operations, pythonnumpy

Source: Internet
Author: User
Tags python list

Python Numpy array initialization and basic operations, pythonnumpy

Python is an advanced, dynamic, and multi-generic programming language. Python code often looks like pseudo code, so you can use a few lines of highly readable code to implement a very powerful idea.

I. Basics:

The main data type of Numpy is ndarray, which is a multi-dimensional array. It has the following attributes:

Ndarray. ndim: dimension of the array
Ndarray. shape: the size of each dimension of the array.
Ndarray. size: Number of all elements in the array
Ndarray. dtype: type of elements in the array (numpy. int32, numpy. int16, and numpy. float64)
Ndarray. itemsize: Each element occupies several bytes.

Example:

>>> import numpy as np>>> a = np.arange(15).reshape(3, 5)>>> aarray([[ 0, 1, 2, 3, 4],    [ 5, 6, 7, 8, 9],    [10, 11, 12, 13, 14]])>>> a.shape(3, 5)>>> a.ndim2>>> a.dtype.name'int64'>>> a.itemsize8>>> a.size15>>> type(a)<type 'numpy.ndarray'>>>> b = np.array([6, 7, 8])>>> barray([6, 7, 8])>>> type(b)<type 'numpy.ndarray'>
2. Create an array:

Use the array Function to convert tuple and list to array:

>>> import numpy as np>>> a = np.array([2,3,4])>>> aarray([2, 3, 4])>>> a.dtypedtype('int64')>>> b = np.array([1.2, 3.5, 5.1])>>> b.dtypedtype('float64')

Multi-dimensional array:

>>> b = np.array([(1.5,2,3), (4,5,6)])>>> barray([[ 1.5, 2. , 3. ],    [ 4. , 5. , 6. ]])

Specify the type when generating the array:

>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )>>> carray([[ 1.+0.j, 2.+0.j],    [ 3.+0.j, 4.+0.j]])

Generate an array and assign it a special value:

Ones: full 1
Zeros: All 0
Empty: Random Number, depending on memory

>>> np.zeros( (3,4) )array([[ 0., 0., 0., 0.],    [ 0., 0., 0., 0.],    [ 0., 0., 0., 0.]])>>> np.ones( (2,3,4), dtype=np.int16 )        # dtype can also be specifiedarray([[[ 1, 1, 1, 1],    [ 1, 1, 1, 1],    [ 1, 1, 1, 1]],    [[ 1, 1, 1, 1],    [ 1, 1, 1, 1],    [ 1, 1, 1, 1]]], dtype=int16)>>> np.empty( (2,3) )                 # uninitialized, output may varyarray([[ 3.73603959e-262,  6.02658058e-154,  6.55490914e-260],    [ 5.30498948e-313,  3.14673309e-307,  1.00000000e+000]])

Generate an even array:

Arange (minimum value, maximum value, step size) (Left closed and right open)
Linspace (minimum, maximum, number of elements)

>>> np.arange( 10, 30, 5 )array([10, 15, 20, 25])>>> np.arange( 0, 2, 0.3 )         # it accepts float argumentsarray([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])>>> np.linspace( 0, 2, 9 )         # 9 numbers from 0 to 2array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])>>> x = np.linspace( 0, 2*pi, 100 )    # useful to evaluate function at lots of points
III. Basic operations:

The entire array is involved in the operation in order:

>>> a = np.array( [20,30,40,50] )>>> b = np.arange( 4 )>>> barray([0, 1, 2, 3])>>> c = a-b>>> carray([20, 29, 38, 47])>>> b**2array([0, 1, 4, 9])>>> 10*np.sin(a)array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])>>> a<35array([ True, True, False, False], dtype=bool)

The two dimensions still use the * symbol to multiply by position one by one. To represent matrix multiplication, use dot:

>>> A = np.array( [[1,1],...       [0,1]] )>>> B = np.array( [[2,0],...       [3,4]] )>>> A*B             # elementwise productarray([[2, 0],    [0, 4]])>>> A.dot(B)          # matrix productarray([[5, 4],    [3, 4]])>>> np.dot(A, B)        # another matrix productarray([[5, 4],    [3, 4]])

Built-in functions (min, max, sum), and axis can be used to specify which dimension to perform operations:

>>> b = np.arange(12).reshape(3,4)>>> barray([[ 0, 1, 2, 3],    [ 4, 5, 6, 7],    [ 8, 9, 10, 11]])>>>>>> b.sum(axis=0)              # sum of each columnarray([12, 15, 18, 21])>>>>>> b.min(axis=1)              # min of each rowarray([0, 4, 8])>>>>>> b.cumsum(axis=1)             # cumulative sum along each rowarray([[ 0, 1, 3, 6],    [ 4, 9, 15, 22],    [ 8, 17, 27, 38]])

Numpy also provides many global functions

>>> B = np.arange(3)>>> Barray([0, 1, 2])>>> np.exp(B)array([ 1.    , 2.71828183, 7.3890561 ])>>> np.sqrt(B)array([ 0.    , 1.    , 1.41421356])>>> C = np.array([2., -1., 4.])>>> np.add(B, C)array([ 2., 0., 6.])
4. Addressing, indexing and traversing:

The traversal Syntax of one-dimensional arrays is similar to that of python list:

>>> a = np.arange(10)**3>>> aarray([ 0,  1,  8, 27, 64, 125, 216, 343, 512, 729])>>> a[2]8>>> a[2:5]array([ 8, 27, 64])>>> a[:6:2] = -1000  # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000>>> aarray([-1000,   1, -1000,  27, -1000,  125,  216,  343,  512,  729])>>> a[ : :-1]                 # reversed aarray([ 729,  512,  343,  216,  125, -1000,  27, -1000,   1, -1000])>>> for i in a:...   print(i**(1/3.))...nan1.0nan3.0nan5.06.07.08.09.0

Multi-dimensional arrays are accessed by specifying an index for each dimension. The order is first high-dimensional and then low-dimensional:

>>> def f(x,y):...   return 10*x+y...>>> b = np.fromfunction(f,(5,4),dtype=int)>>> barray([[ 0, 1, 2, 3],    [10, 11, 12, 13],    [20, 21, 22, 23],    [30, 31, 32, 33],    [40, 41, 42, 43]])>>> b[2,3]23>>> b[0:5, 1]            # each row in the second column of barray([ 1, 11, 21, 31, 41])>>> b[ : ,1]            # equivalent to the previous examplearray([ 1, 11, 21, 31, 41])>>> b[1:3, : ]           # each column in the second and third row of barray([[10, 11, 12, 13],    [20, 21, 22, 23]])When fewer indices are provided than the number of axes, the missing indices are considered complete slices:>>>>>> b[-1]                 # the last row. Equivalent to b[-1,:]array([40, 41, 42, 43])

... Symbol indicates that all dimensions with unspecified indexes are assigned:, which indicates all elements of the dimension in python:

>>> c = np.array( [[[ 0, 1, 2],        # a 3D array (two stacked 2D arrays)...         [ 10, 12, 13]],...        [[100,101,102],...         [110,112,113]]])>>> c.shape(2, 2, 3)>>> c[1,...]                  # same as c[1,:,:] or c[1]array([[100, 101, 102],    [110, 112, 113]])>>> c[...,2]                  # same as c[:,:,2]array([[ 2, 13],    [102, 113]])

Traversal:

If you only want to traverse the entire array, you can directly use:

>>> for row in b:...   print(row)...[0 1 2 3][10 11 12 13][20 21 22 23][30 31 32 33][40 41 42 43]

However, if you want to operate on each element, you need to use the flat attribute, which is an iterator for traversing the entire array.

>>> for element in b.flat:...   print(element)...
Summary

The above section describes the initialization and basic operations of the Python Numpy array. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.