[PYTHON] Numpy [Basic]

I will go through the Numpy documentation. This time it's a pretty basic part. If you want to read the documentation directly, check it out here (https://docs.scipy.org/doc/numpy-1.12.0/numpy-user-1.12.0.pdf)!

0. About installation

I downloaded Python from Anaconda, so Numpy was included from the beginning.

If you don't have it, please download it from here.

1. Basic attributes

--array.ndim: Represents the dimensions of the matrix. It corresponds to how many "[" are followed at the beginning. --array.shape: The shape of the matrix is returned as a tuple. --array.size: The total number of matrix elements. --array.dtype: Represents the data type of the element. In addition to the data types that Python can handle, there are also numpy-specific ones such as np.int64. Also, dtype ='complex' represents a complex number. --array.itemsize: Represents the number of bytes in each element. If it is int64 type, it is 8 bytes.

2. Make a matrix

--Create a matrix from Python data types.

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

>>> array([1, 2, 3],
          [4, 5, 6]])

--np.zeros (matrix form): Takes a tuple as an argument and returns a matrix with all elements 0 --np.ones (matrix form): This returns a matrix in which all elements are 1.

np.zeros((3, 4))

>>> array([0, 0, 0, 0],
          [0, 0, 0, 0],
          [0, 0, 0, 0]])

--np.empty (matrix form): Create a matrix with random elements

np.empty((4, 5))

>>> array([[  0.1 ,   0.15,   0.2 ,   0.25,   0.3 ],
           [  0.4 ,   0.5 ,   0.6 ,   0.8 ,   1.  ],
           [  1.5 ,   2.  ,   2.5 ,   3.  ,   4.  ],
           [  5.  ,   6.  ,   8.  ,  10.  ,  15.  ]])

--np.arange (number of elements): Similar to Python's range (). Make a one-dimensional matrix. --np.arange (a, b, c): In such a form, it starts with a, has elements added by c, and continues until the maximum value less than b is taken.

np.arange(12)

>>> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])


np.arange(10, 30, 5)

>>> array([10, 15, 20, 25])

--np.linspace (a, b, c): Returns a linear matrix with c elements at regular intervals from a to b.

np.linspace(0, 2.0, 9)

>>> array([0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2.])

--np.random.rand (matrix form): Returns a matrix in which each element is 0 or more and 1 or less in the given form. --np.random.randn (matrix form): Same as above, but with integer elements.

--np.fromfunction (function, matrix form [, data type]): Can express the relationship between the number of rows and the number of columns.

np.fromfunction(lambda i,j: i+j, (3, 3), dtype='int64')

>>> array([[0, 1, 2],
           [1, 2, 3],
           [2, 3, 4]])

3. Print the matrix

You can use python's print method to display a clean matrix without commas.

print(np.arange(12).reshape(3, 4))

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

4. Mathematical operations apply to all elements

When you add or multiply a matrix, the operation is applied to all the elements.

a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])

a - b >>> array([9, 18, 27, 36])
b * 2 >>> array([2, 4, 6, 8])
a < 35 >>> array([True, True, True, False])

If you want matrix multiplication, use the dot () function.

A = np.array([[1, 1], [0, 1]])
B = np.array([[2, 0], [3, 4]])


A * B >>>  array([[2, 0],
                  [0, 4]])  #Multiplication of the corresponding elements is performed.

A.dot(B) / np.dot(A, B) >>>  array([[5, 4],
                                    [3, 4]])
a = np.arange(12).reshape(3, 4) >>> array([[0, 1, 2, 3],
                                           [4, 5, 6, 7],
                                           [8, 9, 10, 11]])

a.sum(axis=0) >>> array([12, 15, 18, 21])  #Vertical direction
a.min(axis=1) >>> array([0, 4, 8])  #horizontal direction

5. Matrix index slice iteratorization

Not only linear matrices, but also matrices with multiple dimensions can be handled in the same way as Python's List. However, when treating a matrix with multiple dimensions as an iterator, use the flat attribute. It's similar to using items () when treating a dictionary as an iterator!

A = np.arange(12).reshape(3, 4)

A[(0, 2)] >>>  2  #index
A[1:2, 0:2] >>> array([[4, 5]])  #slice

for element in A.flat:
    print(element)       >>> 0~Up to 11 is printed

6. Change the shape of the matrix

--np.floor (matrix): Round off each element. (I don't think it has anything to do with the shape, but it was written here in the document lol)

--np.ravel (matrix): Converts a matrix to one dimension. --array.reshape (matrix, new form [, order]): Reshape the matrix to the desired shape (order will be described later). --array.T: Give the transposed matrix.

order

The elements of a are read using this index order. ‘C’ means to index the elements in row-major, C-style order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to index the elements in column-major, Fortran-style order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of axis indexing. ‘A’ means to read the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise. ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative. By default, ‘C’ index order is used.

As written, C-style gives priority to row order, and F-style gives priority to column order.

A = np.arange(12).reshape(3, 4)

np.reshape(A, (2, 6), 'C')  >>>  array([[ 0,  1,  2,  3,  4,  5],
                                        [ 6,  7,  8,  9, 10, 11]])
np.reshape(A, (2, 6), 'F')  >>>  array([[ 0,  8,  5,  2, 10,  7],
                                        [ 4,  1,  9,  6,  3, 11]])

Also, there are ʻA-style and K-style`, but I feel that they are not the basics, so I will explain them in future articles if I have the opportunity.

7. Synthesize the matrix

--np.vstack ((matrix 1, matrix 2)): Combine vertically. --np.hstack ((matrix 1, matrix 2)): Combine horizontally.

--np.column_stack ((matrix 1, matrix 2)): Create a two-dimensional matrix for a combination of first-order matrices, and behave the same as hstack for a multidimensional set.

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.array([[1, 2], [3, 4]])
d = np.array([[5, 6], [7, 8]])

np.vstack((a, b))  >>> array([[1, 2, 3],
                              [4, 5, 6]])

np.hstack((a, b))  >>> array([1, 2, 3, 4, 5, 6])

np.column_stack((a, b))  >>> array([[1, 4],
                                    [2, 5],
                                    [3, 6]])

np.column_stack((c, d))  >>> array([[1, 2, 5, 6],
                                    [3, 4, 7, 8]])

--np.newaxis: Create a new dimension.

a = np.array([4, 2])
b = np.array([[1, 2], [3, 4]])


a[:, np.newaxis]  >>> array([[4],
                             [2]])

b[:, np.newaxis] >>> array([[[1, 2]],

                            [[3,4]]])

8. Split the matrix

--np.hsplit (matrix, number): Divide horizontally into the specified number. --np.vsplit (matrix, number): Divide vertically into the specified number.

9. Copy the matrix

--array.view (): A shallow copy in Python. I don't think I use it much. --array.copy (): Deep copy in Python.

Recommended Posts

Numpy [Basic]
Numpy basic calculation memo
Python Basic --Pandas, Numpy-
numpy practice 1
numpy part 1
NumPy basics
Numpy Memorandum_Matrix
numpy tips
About numpy
Basic commands
NumPy axis
Use Numpy
numpy part 2
My Numpy (Python)
Network programming (basic)
where in numpy
RF Python Basic_01
Linux command <Basic 2>
Theano's basic notes
numpy unit test
Flask basic memo
NumPy array manipulation (3)
list and numpy
Basic Python writing
NumPy universal functions
numpy memorandum 1 / np.pad
[Basic] linux command
Basic LINUX commands
#Python basics (#Numpy 1/2)
#Python basics (#Numpy 2/2)
numpy index search
Python3 basic grammar
NumPy array manipulation (1)
Linux command <Basic 1>
[Numpy] Shuffle ndarray
RF Python Basic_02
Python #Numpy basics
numpy non-basic techniques
About Numpy broadcast
Django's basic memorandum
[PyTorch] Sample ① ~ NUMPY ~
Install Numpy + atlas
Flask Basic authentication
[Python] Numpy memo