numpy를 다뤄보면서 사용할 두 가지 라이브러리가 있다. numpy 와 matplotlib이다. 두 개의 라이브러리를 불러보자.
import numpy as np
import matplotlib.pyplot as plt
numpy library를 불러왔으니 다양한 방법으로 ndarray를 생성해보자.
1. np.array
# <in>
x = np.array([1,2,3,4])
print(x)
y = np.array([[2,3,4],[1,2,5]])
print(y)
print(type(y))
# <out>
[1 2 3 4]
[[2 3 4]
[1 2 5]]
<class 'numpy.ndarray'>
2. np.arange()
# <in>
x = np.arange(10)
y = np.arange(1, 10)
z = np.arange(1, 10, 2)
t = np.arange(5, 101, 5)
print(x)
print(y)
print(z)
print(t)
# <out>
[0 1 2 3 4 5 6 7 8 9]
[1 2 3 4 5 6 7 8 9]
[1 3 5 7 9]
[ 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90
95 100]
3. np.one(), np.zeros()
x = np.ones((4, 5))
y = np.ones((2, 3, 4))
z = np.zeros((2, 3, 8, 8))
# x => 4행 5열의 모든 원소가 1인 2차원
# y => 2 x 3 x4인 모든 원소가 1인 3차원
# z => 2 x 3 x 8 x 8인 모든 원소가 0인 4차원
4. np.empty(), np.full()
x = np.empty((3,4))
y = np.full((3,4,2),7)
# y => 모든 원소가 7인 3 x 4 x 2의 3차원 배열
5. np.eye() 단위행렬 생성
# <in>
np.eye(3)
# <out>
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
6. np.linspace()
# <in>
a = np.linspace(1, 10, 3)
b = np.linspace(1, 10, 4)
c = np.linspace(1, 10, 5)
print(a)
print(b)
print(c)
# <out>
[ 1. 5.5 10. ] # 1과 10 사이의 간격이 같은 3개 원소 추출
[ 1. 4. 7. 10.] # 1과 10 사이의 간격이 같은 4개 원소 추출
[ 1. 3.25 5.5 7.75 10. ] # 1과 10사이 간격이 같은 5개 원소 추출
7. reshape() 함수
reshape
함수는 ndarray함수의 형태나 차원을 바꾸기 위해 사용한다.
np.arange()
함수를 사용해 ndarray를 하나 만들어보자.
# <in>
x = np.arange(1, 16) # 1부터 15까지 숫자로 구성된 ndarray
print(x)
x.shape # x는 어떤 모양인가?
x.reshape(3,5) # x를 3,5 2차원 배열로 변경해라
# <out>
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
Out[9]:
array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]])
reshape
함수를 사용할 때, 기존의 ndarray의 원소의 개수와 reshape
을 사용해 변경하고자 하는 배열에서 필요로하는 원소의 개수가 같아야만 한다.
'python > numpy' 카테고리의 다른 글
6. axis의 이해 - axis를 파라미터로 갖는 함수 - (0) | 2023.02.16 |
---|---|
5. numpy ndarray 기본함수 사용 (0) | 2023.02.15 |
4. ndarray -데이터 형태 바꾸기(reshape,flatten)- (0) | 2023.02.15 |
3. ndarray - 인덱싱_슬라이싱 (0) | 2023.02.15 |
2. numpy - random 서브모듈 함수 - (0) | 2023.02.15 |