| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
- python
- 파이썬
- 타이타닉 데이터
- sklearn
- 파이썬 제어문
- Data pre-processing
- Machine Learning
- 판다스
- K평균군집화
- 파이썬 객체 지향 프로그래밍
- python control statement
- Naive Bayes
- pandas
- 파이썬 크롤러
- 넘파이
- 순회 크롤러
- 제어문
- 파이썬 크롤링
- control statement
- Python crawler
- dataframe
- 나이브베이즈
- Titanic data set
- 머신러닝
- 사이킷런
- scikit-learn
- 배열
- KMeans Clustering
- NumPy
- ML
- Today
- Total
Try to 개발자 EthanJ의 성장 로그
Numpy array Manipulation 넘파이 배열 변형 본문
Numpy array Manipulating
넘파이 배열 변형
import numpy as np
def np_print(nparr):
print('''
type : {}
shape : {}
dimension : {}
dtype : {}
data :\n {}
'''.format(type(nparr), nparr.shape, nparr.ndim, nparr.dtype, nparr))
1. 배열 정렬(sorting)¶
arr.sort()method : axis를 기준으로 요소를 오름차순 정렬- default:
axis=-1: 현재 배열의 마지막 axis axis=0: 열 단위 정렬axis=1: 행 단위 정렬- 원본 객체에 정렬 결과가 반영됨
- default:
np.sort(arr): axis를 기준으로 요소를 오름차순 정렬- default
axis=-1: 현재 배열의 마지막 axis axis=0: 열 단위 정렬axis=1: 행 단위 정렬- 정렬된 새로운 배열을 반환함 > 원본 객체 변화 없음
- default
np.argsort(arr): 정렬 순서를 반환- default:
axis=-1: 현재 배열의 마지막 axis axis=0: 열 단위 정렬axis=1: 행 단위 정렬
- default:
arr_1d = np.arange(0, 5)
np_print(arr_1d)
type : <class 'numpy.ndarray'>
shape : (5,)
dimension : 1
dtype : int32
data :
[0 1 2 3 4]
- reverse
arr_1d = arr_1d[::-1]
arr_1d
array([4, 3, 2, 1, 0])
- 난수 패턴 고정
np.random.seed(20)
arr_5 = np.random.randint(0, 10, size=(5))
np_print(arr_5)
type : <class 'numpy.ndarray'>
shape : (5,)
dimension : 1
dtype : int32
data :
[3 9 4 6 7]
arr_2d = np.random.randint(1, 20, size=(3, 4))
np_print(arr_2d)
type : <class 'numpy.ndarray'>
shape : (3, 4)
dimension : 2
dtype : int32
data :
[[ 3 1 9 17]
[ 7 7 17 10]
[ 6 8 6 3]]
1.1. np.sort(arr, axis=-1)¶
np.sort(arr)method : axis를 기준으로 요소를 오름차순 정렬- default:
axis=-1: 현재 배열의 마지막 axis axis=0: 열 단위 정렬axis=1: 행 단위 정렬- 원본 객체에 정렬 결과가 반영됨
- default:
np_print(np.sort(arr_1d))
np_print(arr_1d)
type : <class 'numpy.ndarray'>
shape : (5,)
dimension : 1
dtype : int32
data :
[0 1 2 3 4]
type : <class 'numpy.ndarray'>
shape : (5,)
dimension : 1
dtype : int32
data :
[4 3 2 1 0]
1.2. arr.sort(axis=-1)¶
default:
axis=-1: 현재 배열의 마지막 axisaxis=0: 열 단위 정렬axis=1: 행 단위 정렬- 원본 객체에 정렬 결과가 반영됨
np_print(arr_2d)
arr_2d.sort()
np_print(arr_2d)
type : <class 'numpy.ndarray'>
shape : (3, 4)
dimension : 2
dtype : int32
data :
[[ 3 1 9 17]
[ 7 7 17 10]
[ 6 8 6 3]]
type : <class 'numpy.ndarray'>
shape : (3, 4)
dimension : 2
dtype : int32
data :
[[ 1 3 9 17]
[ 7 7 10 17]
[ 3 6 6 8]]
np_print(arr_5)
type : <class 'numpy.ndarray'>
shape : (5,)
dimension : 1
dtype : int32
data :
[3 9 4 6 7]
np.argsort(arr_5)
array([0, 2, 3, 4, 1], dtype=int64)
arr_5[np.argsort(arr_5)]
array([3, 4, 6, 7, 9])
$0 \leq x < 1$, random float data, 3 rows X 3 columns array
arr_x = np.random.random(size=(3, 3))
arr_y = np.random.random(size=(3, 3))
np_print(arr_x)
np_print(arr_y)
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : float64
data :
[[0.11669374 0.7512807 0.23921822]
[0.25480601 0.85762553 0.94977903]
[0.56168686 0.17878052 0.77025193]]
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : float64
data :
[[0.49238104 0.63125307 0.83949792]
[0.4610394 0.49794007 0.67941112]
[0.65078591 0.26879524 0.06732467]]
- 기본 방향
axis=-1==axis=1: column의 축 방향, $\rightarrow$, row별, 행별 정렬

np_print(arr_x)
np.sort(arr_x)
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : float64
data :
[[0.11669374 0.7512807 0.23921822]
[0.25480601 0.85762553 0.94977903]
[0.56168686 0.17878052 0.77025193]]
array([[0.11669374, 0.23921822, 0.7512807 ],
[0.25480601, 0.85762553, 0.94977903],
[0.17878052, 0.56168686, 0.77025193]])
axis=0: row의 축 방향, $\downarrow$, column별, 열별 정렬

np_print(arr_x)
np_print(np.sort(arr_x, axis=0))
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : float64
data :
[[0.11669374 0.7512807 0.23921822]
[0.25480601 0.85762553 0.94977903]
[0.56168686 0.17878052 0.77025193]]
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : float64
data :
[[0.11669374 0.17878052 0.23921822]
[0.25480601 0.7512807 0.77025193]
[0.56168686 0.85762553 0.94977903]]
- $0 \leq x < 24$, int data arr
arr_24 = np.arange(0, 24)
np_print(arr_24)
type : <class 'numpy.ndarray'>
shape : (24,)
dimension : 1
dtype : int32
data :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
- 1차원 배열 indexing:
index=1item 접근
arr_24[1]
1
- 1차원 배열 indexing > last index item 접근
arr_24[-1]
23
- 1차원 배열 indexing > item value 수정
arr_24[-1] = 100
print(arr_24)
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 100]
reshape(4, 6)
arr_re = arr_24.reshape(4, 6)
np_print(arr_re)
type : <class 'numpy.ndarray'>
shape : (4, 6)
dimension : 2
dtype : int32
data :
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[ 12 13 14 15 16 17]
[ 18 19 20 21 22 100]]
- 하나의 행에 접근:
arr[row index]
>index=0: 첫 번째 행
arr_re[0]
array([0, 1, 2, 3, 4, 5])
- ndarray item indexing >
arr[row index][column index]
arr_re[0][1]
1
하나의 열에 접근 = 모든 행에 대해서 하나의 열에 접근:
arr[:, column index]= 모든 행에 대해(첫 번째 parameter=
:), column index에 접근> return
ndim=1ndarray
np_print(arr_re[:, 2])
type : <class 'numpy.ndarray'>
shape : (4,)
dimension : 1
dtype : int32
data :
[ 2 8 14 20]
- 2차원 배열 하나의 값에 접근
arr[row index][column index]==arr[row index, column index]
print(arr_re[2][2])
print(arr_re[2, 2])
14 14
2.2. Integer array indexing¶
- Integer array indexing allows selection of arbitrary items in the array based on their N-dimensional index. Each integer array represents a number of indices into that dimension.
- 2차원 배열 여러개의 행 조회: list indexing:
arr[[index r1, index r2]]
arr_re[[0, 1]]
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11]])
- 2차원 배열 여러개의 열 조회:
arr[:, [index c1, index c2]]
arr_re[:, [2, 3]]
array([[ 2, 3],
[ 8, 9],
[14, 15],
[20, 21]])
row index=0, 2>column index=3, 5
arr_re[[0, 2]][:, [3, 5]]
array([[ 3, 5],
[15, 17]])
2차원 배열 indexing을 통한 value 수정
하나의 row, column에 대해 모두 동일한 value로 수정
: 전달하는 value를 scalar value로 전달서로 다른 값으로 수정: 배열 shape에 맞춰서 data 전달
- 하나의 값(scalar value)로 수정: scalar value 대입
arr_re[1] = 10
np_print(arr_re)
type : <class 'numpy.ndarray'>
shape : (4, 6)
dimension : 2
dtype : int32
data :
[[ 0 1 2 3 4 5]
[ 10 10 10 10 10 10]
[ 12 13 14 15 16 17]
[ 18 19 20 21 22 100]]
- 서로 다른 값으로 수정: shape같은 배열 대입
print(arr_re[:, 2].shape)
arr_re[:, 2] = [10, 11, 12, 13]
np_print(arr_re)
(4,)
type : <class 'numpy.ndarray'>
shape : (4, 6)
dimension : 2
dtype : int32
data :
[[ 0 1 10 3 4 5]
[ 10 10 11 10 10 10]
[ 12 13 12 15 16 17]
[ 18 19 13 21 22 100]]
3차원 배열 생성:
shape=(page, row, column)shape=(2, 4, 3)배열
arr_3d = np.arange(24).reshape(2, 4, 3)
np_print(arr_3d)
type : <class 'numpy.ndarray'>
shape : (2, 4, 3)
dimension : 3
dtype : int32
data :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]]]
- 3차원 배열 인덱싱:
ndarr[면, 행, 열]
page index=0
arr_3d[0]
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
page index=0,row index=1
arr_3d[0][1]
array([3, 4, 5])
page index=0,row index=1,column index=2
arr_3d[0][1][2]
5
스칼라 연산을 통한 single value로 수정
- 배열의 1번 면:
value=0으로 일괄 변경
- 배열의 1번 면:
np_print(arr_3d)
arr_3d[1] = 0
np_print(arr_3d)
type : <class 'numpy.ndarray'>
shape : (2, 4, 3)
dimension : 3
dtype : int32
data :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[12 13 14]
[15 16 17]
[18 19 20]
[21 22 23]]]
type : <class 'numpy.ndarray'>
shape : (2, 4, 3)
dimension : 3
dtype : int32
data :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]]
하나의 면에 대해 행 별로 서로 다른 값으로 수정 > 행 shape 맞춰서 입력
page index=1,row index=0:arr[1, 0]
## arr_3d[1][0][:] = [10, 20, 30]
arr_3d[1, 0] = [10, 20, 30]
np_print(arr_3d)
type : <class 'numpy.ndarray'>
shape : (2, 4, 3)
dimension : 3
dtype : int32
data :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[10 20 30]
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]]
- 3 X 4 배열 대입
arr_3d[1] = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90],
[100, 110, 120]
]
np_print(arr_3d)
type : <class 'numpy.ndarray'>
shape : (2, 4, 3)
dimension : 3
dtype : int32
data :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[ 10 20 30]
[ 40 50 60]
[ 70 80 90]
[100 110 120]]]
- 기존 indexing 방법:
arr[page, row, col]
arr_3d[1, 3, 2]
120
- 3차원 배열도 Integer array indexing 가능
배열
(0행, 0열), (1행, 1열), (2행, 2열)추출>
arr[page, [[0, 1, 2], [0, 1, 2]]
arr_3d[0, [0, 1, 2], [0, 1, 2]]
array([0, 4, 8])
arr_3d[0][[0, 1, 2], [0, 1, 2]]
array([0, 4, 8])
np_print(arr_3d)
type : <class 'numpy.ndarray'>
shape : (2, 4, 3)
dimension : 3
dtype : int32
data :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[ 10 20 30]
[ 40 50 60]
[ 70 80 90]
[100 110 120]]]
arr[page, row, column]> if 여러 단위를 조회: 2-dim integer list input3-dim list input > loop in 2-dim list
np_print(arr_3d[0, [[0, 1, 2], [0, 2, 3]]])
type : <class 'numpy.ndarray'>
shape : (2, 3, 3)
dimension : 3
dtype : int32
data :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 0 1 2]
[ 6 7 8]
[ 9 10 11]]]
2.3. 슬라이싱(slicing) : 여러 개의 요소에 대해 참조¶
axis별로 범위 지정from_index: 시작 인덱스(포함), default:0> 생략 가능to_index: 종료 인덱스(미포함), defualt:마지막 index=-1> 생략 가능step: index 간격 지정, default:1> 생략 가능
column만 조회하는 경우 : 전체 row에 slicing으로 접근 후 특정 column을 조회
- 0부터 23까지 1씩 증가하는 정수 data를 가지는 1차원 배열 생성
arr_24 = np.arange(24)
np_print(arr_24)
type : <class 'numpy.ndarray'>
shape : (24,)
dimension : 1
dtype : int32
data :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
- 1차원 배열 slicing > 1번부터 4번까지 접근
arr_24[1:5]
array([1, 2, 3, 4])
- index 1부터 index 14까지 step 2로 접근
arr_24[1:15:2]
array([ 1, 3, 5, 7, 9, 11, 13])
- 6 X 4, 2차원 배열 생성
arr_2d = arr_24.reshape(6, 4)
np_print(arr_2d)
type : <class 'numpy.ndarray'>
shape : (6, 4)
dimension : 2
dtype : int32
data :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]
- 2차원 배열 slicing:
arr[row(, col, step)]
- 0행부터 3행까지 접근
arr_2d[0:4]
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
- 1행부터 4행, 2열부터 3열 접근
arr_2d[1:5, 2:4]
array([[ 6, 7],
[10, 11],
[14, 15],
[18, 19]])
- 2차원 배열 slicing을 통한 value 수정
part_arr = arr_2d[1:5, 2:4]
np_print(part_arr)
type : <class 'numpy.ndarray'>
shape : (4, 2)
dimension : 2
dtype : int32
data :
[[ 6 7]
[10 11]
[14 15]
[18 19]]
row index=0,column index=-1제외하고 모든 item을 99로 수정
part_arr[1:, :-1] = 99
np_print(part_arr)
type : <class 'numpy.ndarray'>
shape : (4, 2)
dimension : 2
dtype : int32
data :
[[ 6 7]
[99 11]
[99 15]
[99 19]]
- slicing: shallow copy > 원본 ndarray 변경
np_print(arr_2d)
type : <class 'numpy.ndarray'>
shape : (6, 4)
dimension : 2
dtype : int32
data :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 99 11]
[12 13 99 15]
[16 17 99 19]
[20 21 22 23]]
- 2차원 배열 slicing: 연속되지 않은 범위의 열에 대한 인덱싱
step 1. 전체 행에 대해서 접근
step 2. 여러 개의 열 indexing 배열 전달
전체 row+column index=1, 3
np_print(arr_2d)
np_print(arr_2d[:, [1, 3]])
type : <class 'numpy.ndarray'>
shape : (6, 4)
dimension : 2
dtype : int32
data :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 99 11]
[12 13 99 15]
[16 17 99 19]
[20 21 22 23]]
type : <class 'numpy.ndarray'>
shape : (6, 2)
dimension : 2
dtype : int32
data :
[[ 1 3]
[ 5 7]
[ 9 11]
[13 15]
[17 19]
[21 23]]
> 연습문제¶
아래 정보는 학생들의 학번, 영어 성적, 국어 성적, 수학 성적 정보 입니다.
해당 정보를 첫번째 행(row)에 학번, 두번째 행에 영어 성적, 세번째 행에 국어 성적, 네번째 행에 수학 성적을 저장한 배열로 만들고
학생별로 영어 성적을 오름차순 기준으로 각 열(column)을 정렬하세요.
score = [[1, 2, 3, 4],
[70, 97, 45, 56],
[87, 84, 33, 67],
[46, 60, 75, 78]]
arr_score = np.array(score)
sort_idx = np.argsort(arr_score[1])
print(sort_idx)
arr_score[:, sort_idx]
[2 3 0 1]
array([[ 3, 4, 1, 2],
[45, 56, 70, 97],
[33, 67, 87, 84],
[75, 78, 46, 60]])
2.4. 조건 색인(boolean indexing)¶
배열의 item에 대해 조건을 적용 > return bool item array(
TrueorFalse)True인 item, 조건을 만족하는 item만 조회 가능
- scalar 연산: 10보다 큰 요소 조회
arr_2d
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 99, 11],
[12, 13, 99, 15],
[16, 17, 99, 19],
[20, 21, 22, 23]])
arr_2d > 10
array([[False, False, False, False],
[False, False, False, False],
[False, False, True, True],
[ True, True, True, True],
[ True, True, True, True],
[ True, True, True, True]])
- boolean indexing:
arr[arr을 포함한 조건식]
arr_2d[arr_2d > 10]
array([99, 11, 12, 13, 99, 15, 16, 17, 99, 19, 20, 21, 22, 23])
np_print(arr_2d[arr_2d > 10])
type : <class 'numpy.ndarray'>
shape : (14,)
dimension : 1
dtype : int32
data :
[99 11 12 13 99 15 16 17 99 19 20 21 22 23]
짝수인 item만 남기기
2개 이상의 조건: 각 조건 ( ) bracket 걸고, and =
&, or =|로 연결
arr_2d[(arr_2d % 2 == 0) & (arr_2d != 0)]
array([ 2, 4, 6, 8, 12, 16, 20, 22])
> 연습문제¶
조건색인을 활용해 공무원시험의 합격자 평균을 구해주세요.
합격점수는 60점 이상입니다. 아래는 시험 점수 결과입니다.
[31, 30, 55, 34, 83, 75, 86, 60, 94, 80, 42, 37, 73, 80, 30, 65, 34, 55, 56, 51]
score_arr = np.array([31, 30, 55, 34, 83, 75, 86, 60, 94,
80, 42, 37, 73, 80, 30, 65, 34, 55, 56, 51])
score_arr[score_arr >= 60].mean()
77.33333333333333
3. 배열 복사¶
indexing, slicing된 배열 > 원본 배열과 종속적인 object: shallow copy
arr[:],arr.copy(),np.copy(arr)
> 원본 배열과 독립적인 배열 object 생성: deep copy
arr_1 = [1, 2, 3]
arr_2 = [1, 2, 3]
arr_3 = np.arange(0, 4).reshape(2, 2)
- shallow copy
arr_s = arr_1
arr_s[0] = 10
print(arr_1)
[10, 2, 3]
- deep copy
- array slicing
arr[:]
print(arr_2)
arr_s = arr_2[:]
arr_s[0] = 10
print(arr_s)
print(arr_2)
[1, 2, 3] [10, 2, 3] [1, 2, 3]
arr.copy()
print(arr_3)
arr_c = arr_3.copy()
arr_c[0][1] = 10
print(arr_c)
print(arr_3)
[[0 1] [2 3]] [[ 0 10] [ 2 3]] [[0 1] [2 3]]
np.copy(arr)
print(arr_3)
arr_n = np.copy(arr_3)
arr_n[1][0] = 20
print(arr_n)
print(arr_3)
[[0 1] [2 3]] [[ 0 1] [20 3]] [[0 1] [2 3]]
arr_org = np.arange(1, 13).reshape(3, 4)
arr_org
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
arr_org.T
array([[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11],
[ 4, 8, 12]])
arr_org
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
4.2. 배열 형태 변경¶
arr.ravel(),np.ravel(arr)다차원 배열을 1차원 배열로 변환
np.ravel(arr): deep copyarr.ravel(): shallow copy
arr.reshape(new_shape),np.reshape(arr, new_shape)원본 array instance의 shape를 변경
변경하려는 shape의 전체 item 개수(size)와 원본 배열의 size는 동일해야 함
변경하려는 shape(tuple type)의 한 item은
-1로 대체 가능,
다른 item을 기준으로 계산되어 사용됨reshape()method가 반환하는 array의 item이 변경
> 원본 배열에도 반영: deep copy
- 다차원 배열을 1차원 배열로 전환
arr_arv = arr_org.ravel()
arr_org
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
arr_arv
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
arr.ravel(): return array item 수정 시 > 원본도 수정 (shallow copy)
arr_arv[0] = 10
print(arr_arv)
print(arr_org)
[10 2 3 4 5 6 7 8 9 10 11 12] [[10 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
arr.reshape(new_shape)shape(tuple) item에
-1사용 시 > 나머지 item 자동 계산
arr_re = arr_org.reshape(-1, 4)
arr_re
array([[10, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
arr.reshape()return array item 수정 시 > 원본 item 수정: shallow copy
arr_re[1, [0, 1]] = [100, 200]
arr_org
array([[ 10, 2, 3, 4],
[100, 200, 7, 8],
[ 9, 10, 11, 12]])
5. item 변환(item manipulation)¶
5.1. resize¶
arr.resize(new_shape): shallow copynp.resize(arr, new_shape): deep copy배열의 구조
shape를 변환, 원본 배열의size와 동일하지 않아도 변환 가능size가 동일할 경우:reshape()method와 동일한 결과더 큰
size일 경우arr.resize(new_shape): 원본 변경O, 모자란 부분을 0으로 채움np.resize(arr, new_shape): 원본 변경X, 모자란 부분을 기존 배열 에서 복사해서 추가공통적으로
new_shape은 tuple로 추가
더 작은
size일 경우: 마지막 남은 요소 삭제
- 1이상 10미만 random int 3 X 5 배열 생성
arr_int = np.random.randint(1, 10, (3, 5))
print(arr_int)
[[7 9 3 2 4] [3 7 5 7 5] [9 7 3 4 2]]
- 변경되는 배열의 item수가 동일한 경우 >
arr.reshape()와 동일하게 동작
arr_int.resize(5, 3)
print(arr_int)
[[7 9 3] [2 4 3] [7 5 7] [5 9 7] [3 4 2]]
변경 후 배열의 item수가 더 많은 경우
np.resize(): 원본 변경X, 기존 배열값에서 복사해서 추가
np_re = np.resize(arr_int, (8, 3))
np_print(np_re)
type : <class 'numpy.ndarray'>
shape : (8, 3)
dimension : 2
dtype : int32
data :
[[7 9 3]
[2 4 3]
[7 5 7]
[5 9 7]
[3 4 2]
[7 9 3]
[2 4 3]
[7 5 7]]
- optional parameter
refcheck=Fasle: 크기가 다를 때0으로 item 초기화
arr_int.resize((8, 3), refcheck=False)
np_print(arr_int)
type : <class 'numpy.ndarray'>
shape : (8, 3)
dimension : 2
dtype : int32
data :
[[7 9 3]
[2 4 3]
[7 5 7]
[5 9 7]
[3 4 2]
[0 0 0]
[0 0 0]
[0 0 0]]
- 변형되는 배열의 item수가 더 적은 경우 > 마지막 요소를 삭제
- 원본 배열과
resize()결과 배열의size가 다르다면 반드시refcheck=False추가
arr_int.resize((3, 3), refcheck=False)
np_print(arr_int)
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : int32
data :
[[7 9 3]
[2 4 3]
[7 5 7]]
5.2. item 추가¶
np.append(arr, values)np.insert(arr, idx, values)
np.append(arr, values, axis=None)- arr 마지막에
values를 추가 - default
axis=None: 1차원 배열로 변형되어 결합 axis=0: 행 방향으로 결합 (단, 열의 개수가 동일해야 함)axis=1: 열 방향으로 결합 (단, 행의 개수가 동일해야 함)- 원본 배열들에 반영되지 않음
- arr 마지막에
- 1이상 10미만, step=1, 3 X 3 배열 arr_a
- 10이상 19미만, step=1, 3 X 3 배열 arr_b
arr_a = np.arange(1, 10).reshape(3, 3)
arr_b = np.arange(10, 19).reshape(3, 3)
np_print(arr_a)
np_print(arr_b)
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : int32
data :
[[1 2 3]
[4 5 6]
[7 8 9]]
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : int32
data :
[[10 11 12]
[13 14 15]
[16 17 18]]
- default:
axis지정하지 않은 경우:np.append(arr1, arr2)>axis=None
arr1,arr2둘 다 1차원으로 변형해서 추가
np.append(arr_a, arr_b)
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18])
axis=0: $\downarrow$, 행의 축 방향, 행 기준 결합 > 열 개수는 동일
np.append(arr_a, arr_b, axis=0)
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
axis=1: $\rightarrow$, 열의 축 방향, 열 기준 결합 > 행 개수는 동일
np.append(arr_a, arr_b, axis=1)
array([[ 1, 2, 3, 10, 11, 12],
[ 4, 5, 6, 13, 14, 15],
[ 7, 8, 9, 16, 17, 18]])
- column의 개수가 다른 배열들의 결합
arr_c = np.arange(30, 45).reshape(3, 5)
np_print(arr_c)
type : <class 'numpy.ndarray'>
shape : (3, 5)
dimension : 2
dtype : int32
data :
[[30 31 32 33 34]
[35 36 37 38 39]
[40 41 42 43 44]]
axis=1: 열의 축 방향, $\rightarrow$, 열 기준 결합, 행 개수 동일
np.append(arr_a, arr_c, axis=1)
array([[ 1, 2, 3, 30, 31, 32, 33, 34],
[ 4, 5, 6, 35, 36, 37, 38, 39],
[ 7, 8, 9, 40, 41, 42, 43, 44]])
axis=0: 행의 축 방향, $\downarrow$, 행 기준 결합 > ValueError
np.append(arr_a, arr_c, axis=0)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_2976\1225623211.py in <module> ----> 1 np.append(arr_a, arr_c, axis=0) <__array_function__ internals> in append(*args, **kwargs) ~\anaconda3\lib\site-packages\numpy\lib\function_base.py in append(arr, values, axis) 4815 values = ravel(values) 4816 axis = arr.ndim-1 -> 4817 return concatenate((arr, values), axis=axis) 4818 4819 <__array_function__ internals> in concatenate(*args, **kwargs) ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the array at index 1 has size 5
- 행 단위(
axis=0) 결합할 수 있는 구조로 변경 >arr.resize(): 열 개수 동일
arr_c.resize((5, 3))
np.append(arr_a, arr_c, axis=0)
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[30, 31, 32],
[33, 34, 35],
[36, 37, 38],
[39, 40, 41],
[42, 43, 44]])
- 행 개수가 다른 배열간의 결합
arr_d = np.arange(90, 102).reshape(4, 3)
np_print(arr_d)
type : <class 'numpy.ndarray'>
shape : (4, 3)
dimension : 2
dtype : int32
data :
[[ 90 91 92]
[ 93 94 95]
[ 96 97 98]
[ 99 100 101]]
axis=0: $\downarrow$, 행의 축 방향, 행 단위 > 열 개수 동일
np_print(arr_b)
np.append(arr_b, arr_d, axis=0)
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : int32
data :
[[10 11 12]
[13 14 15]
[16 17 18]]
array([[ 10, 11, 12],
[ 13, 14, 15],
[ 16, 17, 18],
[ 90, 91, 92],
[ 93, 94, 95],
[ 96, 97, 98],
[ 99, 100, 101]])
axis=1: $\rightarrow$, 열의 축 방향, 열 단위 > 행 개수 동일하게resize()
arr_d.resize(3, 4)
np.append(arr_b, arr_d, axis=1)
array([[ 10, 11, 12, 90, 91, 92, 93],
[ 13, 14, 15, 94, 95, 96, 97],
[ 16, 17, 18, 98, 99, 100, 101]])
np.insert(arr, idx, values, axis=None)- 지정한 인덱스
idx에values를 추가- default:
axis=None: 1차원 배열로 변형 후 해당idx에values추가 axis=0: $\downarrow$, 행의 축 방향, 행 기준 해당idx행에 추가axis=1: $\rightarrow$, 열의 축 방향, 열 기준, 해당idx열에 추가
- default:
- 원본 배열에 반영되지 않음
- 지정한 인덱스
arr_in = np.arange(1, 10).reshape(3, 3)
np_print(arr_in)
type : <class 'numpy.ndarray'>
shape : (3, 3)
dimension : 2
dtype : int32
data :
[[1 2 3]
[4 5 6]
[7 8 9]]
- default:
axis=None지정하지 않는 경우: 1차원 배열로 변형 후 지정 index에 값 추가
np.insert(arr_in, 2, [10, 11])
array([ 1, 2, 10, 11, 3, 4, 5, 6, 7, 8, 9])
np.insert()> 원본 배열은 유지: deep copy
arr_in
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
axis=0: $\downarrow$, 행의 축 방향, 행 추가
- scalar값 추가 > row 단위로 BroadCasting 발생
np.insert(arr_in, 1, 100, axis=0)
array([[ 1, 2, 3],
[100, 100, 100],
[ 4, 5, 6],
[ 7, 8, 9]])
axis=1: $\rightarrow$, 열의 축 방향, 열 추가
np.insert(arr_in, 1, 30, axis=1)
array([[ 1, 30, 2, 3],
[ 4, 30, 5, 6],
[ 7, 30, 8, 9]])
각각 다른 item values로 row or column 추가하기
item의 개수를 동일하게 설정: 축을 기준으로 item 개수 결정 >
axis로 축 설정
np.insert(arr_in, 3, [10, 20, 30], axis=0)
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 20, 30]])
5.3. item 삭제¶
np.delete(arr, idx, axis=None)지정한 인덱스
idx에 해당하는 item 삭제default:
axis=None> 1차원 배열로 변형 후 해당idx의 item 삭제axis=0: 행의 축 방향, 해당하는 행 삭제axis=1: 열의 축 방향, 해당 열 삭제
원본 배열에 반영되지 않음
arr_del = np.arange(12).reshape(3, 4)
np_print(arr_del)
type : <class 'numpy.ndarray'>
shape : (3, 4)
dimension : 2
dtype : int32
data :
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
- default:
axis=None: 1차원 배열로 변환 후idx에 해당하는 item 삭제
np.delete(arr_del, 2)
array([ 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11])
- 원본 배열 변경 X
arr_del
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
axis=0: 행의 축 방향, 행 기준, 행 삭제
np.delete(arr_del, 1, axis=0)
array([[ 0, 1, 2, 3],
[ 8, 9, 10, 11]])
axis=1: 열의 축 방향, 열 기준, 열 삭제
np.delete(arr_del, 2, axis=1)
array([[ 0, 1, 3],
[ 4, 5, 7],
[ 8, 9, 11]])
arr_a = np.arange(1, 7).reshape(2, 3)
arr_b = np.arange(7, 13).reshape(2, 3)
arr_c = np.arange(13, 23).reshape(2, 5)
arr_d = np.arange(23, 38).reshape(5, 3)
np_print(arr_a)
np_print(arr_b)
np_print(arr_c)
np_print(arr_d)
type : <class 'numpy.ndarray'>
shape : (2, 3)
dimension : 2
dtype : int32
data :
[[1 2 3]
[4 5 6]]
type : <class 'numpy.ndarray'>
shape : (2, 3)
dimension : 2
dtype : int32
data :
[[ 7 8 9]
[10 11 12]]
type : <class 'numpy.ndarray'>
shape : (2, 5)
dimension : 2
dtype : int32
data :
[[13 14 15 16 17]
[18 19 20 21 22]]
type : <class 'numpy.ndarray'>
shape : (5, 3)
dimension : 2
dtype : int32
data :
[[23 24 25]
[26 27 28]
[29 30 31]
[32 33 34]
[35 36 37]]
- default:
axis=0> 행의 축 방향, 행 기준 배열 결합: 열 개수 동일해야 함
np.concatenate((arr_a, arr_b))
array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
axis=1: 열의 축 방향, 열 기준 배열 결합: 행 개수 동일해야 함
np.concatenate((arr_a, arr_b), axis=1)
array([[ 1, 2, 3, 7, 8, 9],
[ 4, 5, 6, 10, 11, 12]])
- 행의 축 방향 결합 > 열 개수 동일해야 함
np_print(arr_a)
np_print(arr_c)
type : <class 'numpy.ndarray'>
shape : (2, 3)
dimension : 2
dtype : int32
data :
[[1 2 3]
[4 5 6]]
type : <class 'numpy.ndarray'>
shape : (2, 5)
dimension : 2
dtype : int32
data :
[[13 14 15 16 17]
[18 19 20 21 22]]
np.concatenate(arr_a, arr_c)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_2976\4240204882.py in <module> ----> 1 np.concatenate(arr_a, arr_c) <__array_function__ internals> in concatenate(*args, **kwargs) TypeError: only integer scalar arrays can be converted to a scalar index
- 열방향 결합 > 행 개수 동일해야함
np_print(arr_a)
np_print(arr_d)
type : <class 'numpy.ndarray'>
shape : (2, 3)
dimension : 2
dtype : int32
data :
[[1 2 3]
[4 5 6]]
type : <class 'numpy.ndarray'>
shape : (5, 3)
dimension : 2
dtype : int32
data :
[[23 24 25]
[26 27 28]
[29 30 31]
[32 33 34]
[35 36 37]]
np.concatenate(arr_a, arr_d)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_2976\3187866801.py in <module> ----> 1 np.concatenate(arr_a, arr_d) <__array_function__ internals> in concatenate(*args, **kwargs) TypeError: only integer scalar arrays can be converted to a scalar index
6.2. 배열 가르기 np.split()¶
np.split(arr, indices_or_sections, axis=0)default:
axis=0: 행의 축 방향, 행 단위로 분리axis=1: 열의 축 방향, 열 단위로 분리- 원본 배열은 변경되지 않음
arr_spl = np.arange(1, 37).reshape(6, 6)
arr_spl
array([[ 1, 2, 3, 4, 5, 6],
[ 7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18],
[19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36]])
axis=0: 행의 축 방향, 행 단위 분리
- second parameter type ==
list: 위치 및 개수 지정, 균등하지 않게 분리
np.split(arr_spl, [1, 2, 3])
[array([[1, 2, 3, 4, 5, 6]]),
array([[ 7, 8, 9, 10, 11, 12]]),
array([[13, 14, 15, 16, 17, 18]]),
array([[19, 20, 21, 22, 23, 24],
[25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36]])]
axis=1: 열의 축 방향, 열 단위 기준 분리
- second parameter type ==
scalar: 개수 균등하게 분리 > 나머지 없이 나누어 떨어져야 함
np.split(arr_spl, 3, axis=1)
[array([[ 1, 2],
[ 7, 8],
[13, 14],
[19, 20],
[25, 26],
[31, 32]]),
array([[ 3, 4],
[ 9, 10],
[15, 16],
[21, 22],
[27, 28],
[33, 34]]),
array([[ 5, 6],
[11, 12],
[17, 18],
[23, 24],
[29, 30],
[35, 36]])]
'CS & DS > Numpy & Pandas' 카테고리의 다른 글
| Pandas Data Loading 판다스 데이터 적재 (0) | 2022.11.05 |
|---|---|
| Pandas DataFrame 판다스 데이터프레임 (0) | 2022.11.05 |
| Pandas Series 판다스 시리즈 (0) | 2022.11.03 |
| Numpy Operation 넘파이 연산 (0) | 2022.10.30 |
| Basic Numpy 넘파이 기초 (0) | 2022.10.24 |