Numpy(1) : Make Array

Numpy is a module for operating Vector and Matrix.


Install the module

conda install numpy
# If success, there would be no response.

Import the module

import numpy as np
# If success, there would be no response.

Make array from list

import numpy as np

a_list = [1,2,3,4,5]
a_np = np.array(a_list)

print(a_list)
print(a_np)
[1, 2, 3, 4, 5]
[1 2 3 4 5]

There is a difference between list and array. The element of list is divided by comma. In contrast, the element of array is divided by space.


Copy array

import numpy as np

a_np = np.array([1,2,3,4,5])
b_np = a_np
c_np = a_np.copy()

b_np[0] = 99

print(a_np)
print(b_np)
print(c_np)
[99  2  3  4  5]
[99  2  3  4  5]
[1 2 3 4 5]

copy() Method duplicates the original array. This copy is not a reference but a seperate.


Indexing, Slicing array

import numpy as np

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

print(a_np[0])
print(a_np[0:2])
1
[1 2]

Array can be indexed and sliced as similar to list.


Broadcast array

import numpy as np

a_np = np.array([1,2,3,4,5])
b_np = np.array([1,2,3,4,5])
c_np = np.array([1,2,3])

print(a_np + 2)
print(a_np - 2)
print(a_np * 2)
print(a_np / 2)
[3 4 5 6 7]
[-1  0  1  2  3]
[ 2  4  6  8 10]
[0.5 1.  1.5 2.  2.5]

By numpy. we can operate calculation between vector and scala. This is one of the differences from list.


Operate array

import numpy as np

a_np = np.array([1,2,3,4,5])
b_np = np.array([1,2,3,4,5])
c_np = np.array([1,2,3])

print(a_np + b_np)
print(a_np - b_np)
print(a_np * b_np)
print(a_np / b_np)
[ 2  4  6  8 10]
[0 0 0 0 0]
[ 1  4  9 16 25]
[1. 1. 1. 1. 1.]

By numpy, we can operate calculations between vectors. In that, the elements of operands should be in match of each.

좋은 웹페이지 즐겨찾기