The Numpy__python of the Python Scientific Computing Library

Source: Internet
Author: User
Tags arithmetic true true
NumPy
NumPy's core data structure is Ndarray, you can create an n-dimensional array
Characteristics of Ndarray
Ndarray (n-dimensional Array): N-dimensional array

-a multidimensional array of elements of the same type , with the number of elements in advance given a good
-The data type of the element is specified by the Dtype (Data-type) object, and there is only one Dtype type per Ndarray
-The size of the ndarray is fixed, and the size of the array after the array is created will not change ndarray

Array function: Receives an ordinary python sequence and converts it to Ndarray

b = Np.array ([
    [[1,2,3],
    [4,5,6]

])
print (b) out

:
[[1 2 3]
 [4 5 6]]

Zeros function: Creates a fully zero group of the specified length or shape.

D = Np.zeros ((2,3))
print (d) out

:
[[0.  0.  0.]
 [0.  0.  0.]]

Ones function: Creates a full 1 array of the specified length or shape.

E = Np.ones ((3,4))
print (e) out

:
[1.  1.  1.  1.]
 [1.  1.  1.  1.]
 [1.  1.  1.  1.]]

Empty function: Create an array with no specific values (ready to create some uninitialized ndarray multidimensional arrays)

f = Np.empty ((6,6))
print (f)
Ndarray Create basic data Types


Code:

Import NumPy as np
a1 = Np.array (["Python", "Java", "C + +", "PHP"])
print (A1)
A1

Out :

[' Python ' Java ' C + + ' PHP ']
OUT[81]:
Array ([' Python ', ' Java ', ' C + + ', ' PHP '], dtype= ' <u6 ')

Code:

A2 = Np.array (["haha", "hehe", "whirring", "quack"])
print (A2)
A2

Out :

[B ' Python ' B ' Java ' B ' C + + ' B ' PHP ']
OUT[83]:
Array ([b ' Python ', b ' Java ', B ' C + + ', B ' PHP '], dtype= ' | S8 ')
Ndarray Other ways to create

Arange function: A python-like range function that creates a one-dimensional array (without a final value) by specifying a start value , a final value , and a step size .

g = Np.arange (10,50,5)
print (g) #输出: [a]

h = np.arange (30,20,-2)
print (h) #输出: [30 28 26 24 22]

Linspace function: Creates a one-dimensional array by specifying the start value , the end value , and the number of elements , and the data elements of the array conform to the arithmetic progression, which can be specified by the Endpoint keyword to include the final value and the default value

i = np.linspace (0,25,6,endpoint = True)
print (i)  #输出: [  0.   5.  .  25.]

Logspace function: Similar to the Linspace function, but creates a geometric progression array

j = Np.logspace (2,3,5)
print (j) # Output: [  177.827941  316.22776602  562.34132519  1000.  ]

Random function: Fills an array with random numbers, uses the random () function in Numpy.random to create a random element, and the array contains the number of elements determined by the parameter

j = Np.random.random ((2,3,4))
print (j)

output:
[[[0.67133713  0.80188756  0.06388015  0.81575917]
  [0.21830916  0.90382401  0.0095      0.95252789]
  [0.54048634  0.07984948  0.9527077   0.85444074]]

 [[0.15047247  0.14771948  0.425606    0.02572186]
  [0.71512809  0.81017573  0.80882504  0.87543752]
  [0.75518265  0.73766281  0.93846421  0.31309056]]]
Properties of NdarrayDtype: An object used to describe the data type of an array element Astype: To convert the array element data type shape: a tuple of the dimensions of the arrays, that is, the shape size of the array: the total number of elements, that is, the multiplication of the numbers in shape

Ndim: Number of dimensions of the array

C= Np.array ([[[[[[
        1,4,7],[2,5,8]]
    ,
    [
        [3,6,9],[6,6,6]]]
)

print (c)

output:
[[[1 4 7]
  [2 5 8]]

 [[3 6 9]
  [6 6]]]

print (C.ndim)  # The latitude of the array is: 6
print (c.dtype) # array element data type is: Int32
Print (c.shape) # Array of dimensions of each latitude: (2, 2, 3)  The number of elements in the array (c.size) #:

d= c.astype (float)
print (D.dtype) #数组元素数据类型为: float64
Ndarray Modify Array structure
For an already existing Ndarray array object, you can change the structure shape of the array by calling the method that modifies the shape.

-Modify the shape value of the array Ndarray directly, and require the product to be unchanged after modification.
-Directly using the Reshape function to create a new array that changes the size, the shape of the original array remains unchanged, but the new array and the original array share a memory space, modifying the values in the array will have an effect on the other, as well as the number of elements of the new array and the original array.
-When an axis is specified to be-1, the length value of the axis is automatically calculated based on the number of array elements.

Code:

B1 = Np.arange (0,20,2) print (B1) print (b1.size) print (
b1.shape)

Out :

[0  2  4  6  8]
(10,)

Code:

B2 = B1.reshape (2,5)
print (B2)

Out :

[[0  2  4  6  8]
 [10 12 14 16 18]]

Code

B3 = B1.reshape ( -1,2)
print (B3)
b3[2][1] =
print (B1)

Out :

[[0  2]
 [4  6] [8] [A] [+]
 ]
[  0   2   4 6 8 100  18]

Code:

B2.shape = (1,10)
print (B2)

Out :

[[  0   2   4   6   8  18]]
basic operation of NumPy Ndarray The index of multidimensional arrays
C1 =  Np.array ([[[[[
        5,2,4],
        [3,8,2],
    ],
    [
        [6,0,4],
        [0,1,6]]

]

Print (c1[1,0,2])    # out:4
print (c1[0][1][2])  # Out:2
Ndarray Fancy Index

Code:

F1=np.arange. Reshape ((8,4))
print (F1)

Out :

[[0  1  2  3]
 [4 5 6 7  ]
 [8 9  ] [
 19]
  [20] [[
 28 29 30 31]]

Code:

F2 = f1[[2,3,5]] #取第2, 3, 5 line
print (F2)

Out :

[[8  9]
 [EUR] [
 20 21 22 23]]

Code:

F3 = f1[[2,3,5],[1,2,3]]  #分别取第2, 3, 5 lines 1th, 2, 3 element
print (F3) #out: [9 14 23]

Code:

F4 = F1[np.ix_ ([2,3,5],[1,2,3])] #分别取第2 3, 5 rows 1,2,3 column
#f4 = f1[[2,3,5]][:,[1,2,3]]
print (f4)

Out :

[[9]
 [EUR]
 [21 22 23]]
slices of ndarray arraysThe new array obtained by slicing is just a view of the original array, and the original array changes as the values in the new array are changed. Slices of a ndarray array with a slice in Python Ndarray Boolean type index

Code:

D1 = Np.arange (0,12,1)
d1.shape = (3,4)
print (D1)

Out :

[[0  1  2  3] [4 5 6 7  ]
 [8  9 10 11]]

Code:

D2 = D1 < 6
print (D2)

Out :

[[True True to True] [
 true
 to false] [false false]

Code:

Print (D1[d2])
# Print (d1[d1<6])

Out :

[0 1 2 3 4 5]

Code:

Names=np.array ([' Gerry ', ' Tom ', ' John '])
scores=np.array ([
        [98,87,76,65],
        [45,45,66,90],
        [ 87,76,67,91]
    ]
Classs=np.array ([u ' language ', U ' mathematics ', U ' English ', U ' Sports '])

e1 = names== ' Gerry '
print (E1)  # [ True false]
print (Scores[e1].reshape (( -1)) #[98)
print (scores[(names== ' Gerry ') | ( names== ' Tom ')]

Out :

[[The]
 [45 45 66 90]]
Ndarray Array and scalar, array operations

Arrays can perform batch arithmetic operations on each element without looping, a process called vectorization, which replaces loops with array expressions. The vectorization array performs one or two data levels faster than the pure Python method.

Any arithmetic operations between two arrays of equal size will apply their operations to the operations at the element level. In NumPy, an operation between an array of equal size is an element-level operation, that is, only between elements of the same position, and the resulting result consists of a new array with the same position as the operand. The matrix product of Ndarray array

Matrices: Multidimensional Arrays-matrices
Matrix C = Matrix A * matrix B (the number of columns in matrix A must equal the number of rows in matrix B, A and B can be multiplied)

Code

arr1 = Np.array ([[
    [5,2,4],
    [3,8,2],
    [6,0,4],
    [0,1,6]
])

arr2 = Np.array ([
    [[2,4
    ], [ 1,3],
    [3,2]
])

arr = Arr1.dot (arr2)
print (arr)

out

[[A]
 [+]
 [A]
 [19 15]]
Ndarray Array Transpose and axis swappingArray transpose refers to the reset of the shape, and resets its value to an inversion of the original shape tuple, such as the original Shape value: (2,3,4), then the value of the shape of the transposed new tuple is: (4,3,2) for a two-dimensional array (matrix) The transpose of an array is actually a transpose of the matrix. Array transpose can be done by calling the transpose function of the array or the T property

Code:

G1 = Np.arange () reshape (3,4) print (G1)
print (g1.shape)

Out :

[[0  1  2  3]
 [4 5 6 7  ]
 [8  9]]
(3, 4)

Code:

G2 = G1.transpose ()
print (G2)
print (G2.shape)

Out :

[[0  4  8]
 [1  5 9  ] [
 2  6]
 [3 7]  ]
(4, 3)

Code:

G3 = G1. T
Print (G3)
print (G3.shape)

Out :

[[0  4  8]
 [1  5 9  ] [
 2  6]
 [3 7]  ]
(4, 3)
Common Functions Common unary functions

commonly used two meta functions

aggregate Functions

An aggregate function is a function that operates on a set of values (eg. an array) and returns a single value as the result. Of course, aggregate functions can also specify data aggregation operations on a specific axis; The usual aggregation operations are: average, maximum, minimum, variance, and so on.

I1 = Np.array ([
    [[1,2,3,4],
    [5,6,7,8],
    [9,0,-2,-4]
]) print (i1)

print (Np.max)  #最大值
Print (Np.min (i1))  #最小值
print (Np.mean (i1)) #平均值
print (NP.STD (i1)) # Standard deviation
print ( Np.var (I1)) #方差

print (Np.max (I1,axis=1))  #axis = 1 To manipulate the row data
print (Np.mean (i1,axis=0)) #axis = 0 means to manipulate the column data
print (Np.sum (I1,axis=1)) # To sum rows
where function

The WHERE function is the vectorization version of the ternary expression x if condition else y

J1 = Np.array ([1.1,1.2,1.3,1.4])
J2 = Np.array ([2.1,2.2,0.3,2.4])
condition = j1<j2 result1

= [x if c else Y for (x,y,c) in Zip (j1,j2,condition)]
print (RESULT1) # [1.1000000000000001, 1.2, 1.3, 1.3999999999999999]

Print (condition)
#condition为True获取j1中的内容 to get the content in J2
result2 = Np.where (condition,j1,j2)
print ( RESULT2)

Out :

[1.1  1.2  0.3  1.4]
[true to True  False  ]
[1.1 1.2 0.3  1.4]
Unique function

To redo the elements in an array

K1 = Np.array (["A", "B", "C", "E", "B", "C"])
k2 = Np.unique (k1)
print (K2) #[' a ' B ' C ' e ']
the difference between random, RANDN and Rand

Numpy.random.random (Name,a)

This can change the random number you want is the distribution, you can adjust the parameters of random numbers, such as normal distribution can be changed two parameters

Numpy.random.randn (D0, D1, ..., DN)

Returns one or more sample values from the standard normal distribution. 

Numpy.random.rand (D0, D1, ..., DN)

The 
 evenly distributed random samples are located in [0, 1). 

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.