[Scientific / technical calculation by Python] Basic operation of arrays, numpy

Arrays are indispensable in scientific and technical calculations. Perform basic array operations using numpy.

Contents

(1) Creating an array from the "list" (2) Display / retrieval of array elements (3) "Add" and "Concatenate" arrays (4) Sorting of array elements (5) "Four arithmetic operations" of arrays (6) Applying functions to array elements [Addendum] Differences from the Python standard "(multiple) list"


(1) "Create an array from a list

import numpy as np
"""
Creating an "array"
"""
a_list = [0,1,2,3,4,5] # a_Create a list named list and element 0, 1, 2, 3, 4,Store 5
a_array = np.array(a_list)  # a_Make list an "array"

print(a_array)

Result (1)

[0 1 2 3 4 5]


(2) Extraction of array elements

(2)


a_list = [0,1,2,3,4,5] # a_Create a list named list and element 0, 1, 2, 3, 4,Store 5
a_array = np.array(a_list)  # a_Make list an "array"

print(a_array[0]) #Display element zero of the array(Count from zero)   # A
print(a_array[1])  # **No. 1#B

print(a_array[-1]) #Count from the back. From the back-1, -2, ...It is in the order.#C

print(a_array[1:3]) #Element number 1(The second element from the left because it counts from zero)Or create an array up to the third array element#D
print(a_array[2:])  #Element number 2(The third element from the left because it counts from zero)Create an array containing from to one before the last element#D
print(a_array[:4]) #Create an array containing element numbers 0 to 4th array element#F

Result (2)

0 #A 1 #B 5 #C [1 2] #D [2 3 4 5] #E [0 1 2 3] EF

(Note) The alphabet at the end corresponds to the alphabet on the output line of the print function in the above code.


(3) "Add" and "Concatenate" arrays

Let np.append (array, element).

example(3-1)



import numpy as np
a_list = [0,1,2,3,4,5] # a_Create a list named list and element 0, 1, 2, 3, 4,Store 5
a_array = np.array(a_list)  # a_Make list an "array"

a_array = np.append(a_array,10) #element'10'Array a_Add to array
print(a_array)

Result (3-1)

[ 0 1 2 3 4 5 10]

example(3-2)Array concatenation


import numpy as np
a_list = [0,1,2,3,4,5] # a_Create a list named list and element 0, 1, 2, 3, 4,Store 5
a_array = np.array(a_list)  # a_list is "array" a_to array

b_list=[200, 300, 400] #b_Create a list named list and element 200, 300,Store 400
b_array = np.array(b_list) #  b_list to "array" b_to array

a_array = np.append(a_array, b_array) ##Array a_Array b in array_Concatenate arrays
print(a_array)

Result (3-2)

[ 0 1 2 3 4 5 200 300 400]


(4) Sorting of array elements

You can use sort to get an array in which the array elements are arranged in order from the smallest number to the largest number (ascending order). Use the sorted and ** reverse ** options to sort in the reverse (descending order) of sort.

(4)sort


import numpy as np
c_list = [14, 90, 4, 23, 61, 110, 75]
c_array = np.array(c_list)

sorted1=np.sort(c_array) #Array c_Construct an array named sorted1 with arrays arranged in ascending order

sorted2=np.array(sorted(c_array, reverse=True)) #Array c_Build an array named sorted2 with arrays arranged in descending order

print(sorted1)
print(sorted2)

Result (4)

[ 4 14 23 61 75 90 110] [110 90 75 61 23 14 4]


(5) "Four arithmetic operations" of arrays

import numpy as np
"""
"Four arithmetic operations" of arrays
"""
D1_array=np.array([1, 2, 3])
D2_array=np.array([4, 5, 6])

print(D1_array+D2_array) #Addition= numpy.add(D1_array, D2_array) #A
print(D1_array-D2_array) #Subtraction= numpy.subtract(D1_array, D2_array)#B

print(D1_array*D2_array) #Multiply= numpy.multiply(D1_array, D2_array) #C
print(D1_array/D2_array) #division= numpy.divide(D1_array, D2_array) #D

print(D1_array%D2_array) #Surplus= numpy.add(D1_array, D2_array) #E

print(D1_array**D2_array) #Exponentiation numpy.power(D1_array, D2_array) #F

Result (5):

[5 7 9] #A [-3 -3 -3] #B [ 4 10 18] #C [ 0.25 0.4 0.5 ] #D [1 2 3] #E [ 1 32 729] #F

(Note) The alphabet at the end of the list corresponds to the alphabet on the output line of the print function in the above code.


(6) Applying functions to array elements

Example(6)Function mapping


import numpy as np
"""
Applying the same function to array elements
"""
D_array=np.array([1, 2, 3]) #Element 1, 2,Array D with 3_Build array

print(np.cos(D_array))  # D_Evaluate the cos function value with all elements of array as arguments
print(np.sqrt(D_array)) #  D_Sqrt function with all elements of array as arguments(root)Evaluate the value

Result (6)

[ 0.54030231 -0.41614684 -0.9899925 ] [ 1. 1.41421356 1.73205081]


Addendum: Differences between Python standard "(multiple) lists" and numpy's ndarray

An [object] called ndarray created by numpy.array (list) (https://ja.wikipedia.org/wiki/%E3%82%AA%E3%83%96%E3%82%B8%E3%82% A7% E3% 82% AF% E3% 83% 88_ (% E3% 83% 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3 Comparing% E3% 82% B0)) with a list object by python, it has the following features (Reference [1]). Calculation processing can be speeded up by 1 and 2. This is because the overhead during calculation (memory access / time required for function call) is reduced. See reference [1] for details.

  1. Data is stored in a contiguous area of memory (similar to C language and Fortran arrays)
  2. Constructed with elements that basically have the same type structure
  3. The number of elements in each dimension must be equal
  4. Can perform specific operations at high speed on (all) elements in an array

References

[1] Kenji Nakaku, "Introduction to Python for Science and Technology Calculations", Gijutsu-Hyoronsha, 2016.

Recommended Posts

[Scientific / technical calculation by Python] Basic operation of arrays, numpy
[Scientific / technical calculation by Python] Calculation of matrix product by @ operator, python3.5 or later, numpy
[Scientific / technical calculation by Python] Monte Carlo integration, numerical calculation, numpy
[Scientific / technical calculation by Python] Sum calculation, numerical calculation
[Scientific / technical calculation by Python] Histogram, visualization, matplotlib
[Scientific / technical calculation by Python] Lagrange interpolation, numerical calculation
[Scientific / technical calculation by Python] Logarithmic graph, visualization, matplotlib
[Scientific / technical calculation by Python] Polar graph, visualization, matplotlib
[Scientific / technical calculation by Python] Solving (generalized) eigenvalue problem using numpy / scipy, using library
[Scientific / technical calculation by Python] Drawing animation of parabolic motion with locus, matplotlib
[Scientific / technical calculation by Python] Numerical calculation to find the value of derivative (differential)
[Scientific / technical calculation by Python] Analytical solution to find the solution of equation sympy
[Scientific / technical calculation by Python] Drawing of 3D curved surface, surface, wireframe, visualization, matplotlib
[Scientific / technical calculation by Python] 3rd order spline interpolation, scipy
[Scientific / technical calculation by Python] Plot, visualization, matplotlib of 2D data read from file
[Scientific / technical calculation by Python] Drawing, visualization, matplotlib of 2D (color) contour lines, etc.
[Scientific / technical calculation by Python] Numerical solution of second-order ordinary differential equations, initial value problem, numerical calculation
[Scientific / technical calculation by Python] List of usage of (special) functions used in physics by using scipy
[Scientific and technical calculation by Python] Drawing of fractal figures [Sierpinski triangle, Bernsley fern, fractal tree]
[Scientific / technical calculation by Python] Numerical solution of one-dimensional harmonic oscillator problem by velocity Verlet method
[Scientific / technical calculation by Python] Numerical solution of eigenvalue problem of matrix by power method, numerical linear algebra
[Scientific / technical calculation by Python] Numerical integration, trapezoidal / Simpson law, numerical calculation, scipy
[Scientific / technical calculation by Python] Vector field visualization example, electrostatic field, matplotlib
[Scientific / technical calculation by Python] 1D-3D discrete fast Fourier transform, scipy
[Scientific / technical calculation by Python] 2D random walk (drunk walk problem), numerical calculation
[Scientific / technical calculation by Python] Monte Carlo simulation of thermodynamics of 2D Ising spin system by Metropolis method
[Scientific / technical calculation by Python] Solving ordinary differential equations, mathematical formulas, sympy
[Scientific / technical calculation by Python] Derivation of analytical solutions for quadratic and cubic equations, mathematical formulas, sympy
Basic operation list of Python3 list, tuple, dictionary, set
1. Statistics learned with Python 1-2. Calculation of various statistics (Numpy)
Calculation of technical indicators by TA-Lib and pandas
Basic operation of Python Pandas Series and Dataframe (1)
[Scientific / technical calculation by Python] Solving second-order ordinary differential equations by Numerov method, numerical calculation
[Scientific / technical calculation by Python] Plot, visualize, matplotlib 2D data with error bars
[Scientific / technical calculation by Python] Solving one-dimensional Newton equation by the 4th-order Runge-Kutta method
[Python] Operation of enumerate
[Scientific / technical calculation by Python] Solving the boundary value problem of ordinary differential equations in matrix format, numerical calculation
Basic operation of Pandas
python numpy array calculation
Basic knowledge of Python
Python Basic --Pandas, Numpy-
[Scientific / technical calculation by Python] Numerical solution of one-dimensional and two-dimensional wave equations by FTCS method (explicit method), hyperbolic partial differential equations
[Scientific / technical calculation by Python] Generation of non-uniform random numbers giving a given probability density function, Monte Carlo simulation
Sum of multiple numpy arrays (sum)
[Science / technical calculation by Python] Numerical solution of first-order ordinary differential equations, initial value problem, numerical calculation
python> Handling of 2D arrays
Calculation of similarity by MinHash
[Scientific / technical calculation by Python] Wave "beat" and group velocity, wave superposition, visualization, high school physics
I wrote the basic operation of Numpy in Jupyter Lab.
Basic usage of Python f-string
Comparison of calculation speed by implementation of python mpmath (arbitrary precision calculation) (Note)
[Algorithm x Python] Calculation of basic statistics Part2 (mean, median, mode)
[Algorithm x Python] Calculation of basic statistics (total value, maximum value, minimum value)
Visualization of matrix created by numpy
Summary of basic implementation by PyTorch
[Scientific / technical calculation by Python] Numerical solution of two-dimensional Laplace-Poisson equation by Jacobi method for electrostatic potential, elliptic partial differential equation, boundary value problem
[Scientific / technical calculation by Python] Numerical solution of one-dimensional unsteady heat conduction equation by Crank-Nicholson method (implicit method) and FTCS method (positive solution method), parabolic partial differential equation
Basic grammar of Python3 system (dictionary)
Behavior of python3 by Sakura's server
Basic Python operation 2nd: Function (argument)
[Python] Calculation of Kappa (k) coefficient