Numpy 기초
난수 기반 배열 생성
numpy는 난수 발생 및 배열을 생성하는 다음과 같은 numpy.random 모듈을 제공한다.
- np.random.normal
- np.random.rand
- np.random.randn
- np.random.randint
- np.random.random
import numpy as np
import matplotlib.pyplot as plt
def pprint(arr):
print('type : {}'.format(type(arr)))
print('shape : {}, demention : {}, dtype : {}'.format(arr.shape, arr.ndim, arr.dtype))
print("array's Data : \n", arr)
np.random.normal( )
- normal(loc=0.0, scale=1.0, size=None)
- 정규 분포 확률 밀도에서 표본 추출
- loc : 정규 분포의 평균
- scale : 표준편자
mean = 0
std = 1
a = np.random.normal(mean, std, (2, 3))
pprint(a)
type : <class 'numpy.ndarray'>
shape : (2, 3), demention : 2, dtype : float64
array's Data :
[[-0.81666728 0.86587411 0.72678577]
[-2.47332927 -0.7998561 1.41042991]]
data = np.random.normal(0, 1, 10000)
plt.hist(data, bins=100)
plt.show
<function matplotlib.pyplot.show(close=None, block=None)>
np.random.rand( )
- numpy.random.rand(d0, d1, … , dn)
- shapedl (d0, d1, …, dn)인 배열 생성 후 난수로 초기화
- 난수 : 균등분포(Uniform Distribution) 형상으로 표본추출
a = np.random.rand(3, 2)
pprint(a)
type : <class 'numpy.ndarray'>
shape : (3, 2), demention : 2, dtype : float64
array's Data :
[[0.1638656 0.12792174]
[0.2677758 0.85816475]
[0.71601203 0.72992428]]
- 균등한 비율로 표본 추출
- 아래는 균등 분포로 10000개의 표본 추출한 결과를 시각화한 것이다.
- 표본 10000개를 10개의 구간으로 구분했을때 균등분포 형태를 보이고 있다.
data = np.random.rand(10000)
plt.hist(data, bins=10)
plt.show()
np.random.randn( )
- numpy.random.randn(d0, d1, …, dn)
- (d0, d1, …, dn) shape 배열 생성 후 난수로 초기화
- 난수 : 표준 정규 분포(standard normal distribution)에서 표본 추출
a = np.random.randn(2, 4)
pprint(a)
type : <class 'numpy.ndarray'>
shape : (2, 4), demention : 2, dtype : float64
array's Data :
[[-0.31560668 -1.53699715 1.33081214 -0.22791779]
[ 1.07056951 0.5235682 0.46737796 -2.1603113 ]]
- np,random.randn 은 정규 분포로 표본 추출
- 아래는 정규 분포로 10000개를 표본 추출한 결과를 히스토그램으로 표현한 것이다.
- 표본 10000개의 배열을 10개 구간으로 구분했을때 정규 분포 형태를 보이고 있다.
data = np.random.randn(10000)
plt.hist(data, bins = 10)
plt.show()
np.random.randint
- numpy.random.randint(low, high=None, size=None, dtype=’I’)
- 지정된 shape으로 배열을 만들고 low부터 high 미만의 범위에서 정수 표본 추출
a = np.random.randint(5, 10, size = (2, 4))
pprint(a)
type : <class 'numpy.ndarray'>
shape : (2, 4), demention : 2, dtype : int64
array's Data :
[[6 6 7 7]
[7 7 7 5]]
a = np.random.randint(1, size=10)
pprint(a)
type : <class 'numpy.ndarray'>
shape : (10,), demention : 1, dtype : int64
array's Data :
[0 0 0 0 0 0 0 0 0 0]
- -100에서 100의 범위에서 정수를 균등하게 표본 추출한다.
- 균등 분포로 10000개의 표본 추출한 결과를 시각화한것이다.
- 표본 1000개의 배열을 10개의 구간으로 구분했을때 균등한 분포를 보인다.
data = np.random.randint(-100, 100, 10000)
plt.hist(data, bins=10)
plt.show()
np.random.random
- np.random.random(size=None)
- 난수 : 균등 분포에서 표본 추출
a = np.random.random((2, 4))
pprint(a)
type : <class 'numpy.ndarray'>
shape : (2, 4), demention : 2, dtype : float64
array's Data :
[[0.91801448 0.83336041 0.97690668 0.95632603]
[0.85216192 0.22771662 0.339517 0.53920135]]
- np.rnadom.random은 균등 분포로 표본을 추출한다.
- 아래는 정규 분포로 10000개를 표본 추출한 결과를 시각화 한 것입니다.
- 표본 10000개의 배열을 10개 구간으로 구분했을때 정규분포 형태를 보인다.
data = np.random.random(10000)
plt.hist(data, bins=10)
plt.show()
약속된 난수
무작위 수를 만드는 난수는 특정 시작 숫자로부터 난수처럼 보이는 수열을 만드는 알고리즘의 결과이다. 따라서 시작점을 설정함으로써 난수 발생을 재연할 수 있다.
난수의 시작점을 설정하는 함수는 np.random.seed 이다.
np.random.random((2, 2))
array([[0.89388547, 0.34015065],
[0.07278817, 0.76712908]])
np.random.randint(0, 10, (2, 3))
array([[1, 1, 0],
[3, 6, 2]])
np.random.random((2, 2))
array([[0.68182251, 0.21436768],
[0.50504071, 0.87970853]])
np.random.randint(0, 10, (2, 3))
array([[5, 0, 1],
[6, 0, 7]])
- np.random.seed 함루를 이용해 무작위 수 재연
- np.random.seed(100)을 기준으로 동일한 무작위수로 초기화된 배열이 만들어진다.
np.random.seed(100)
np.random.random((2, 2))
array([[0.54340494, 0.27836939],
[0.42451759, 0.84477613]])
np.random.randint(0, 10, (2, 3))
array([[4, 2, 5],
[2, 2, 2]])
numpy 입출력
numpy는 배열 객체를 바이너리 파일 혹은 텍스트 파일에 저장하고 리딩할수 있다.
함수명 | 기능 | 파일포멧 |
---|---|---|
np.save( ) | numpy 배열 객체 1개를 파일에 저장 | 바이너리 |
np.savez( ) | numpy 배열 객체 복수개를 파일에 저장 | 바이너리 |
np.load() | numpy 배열 저장 파일로 부터 객체 로딩 | 바이너리 |
np.loadtxt( ) | 텍스트 파일로부터 배열 로딩 | 텍스트 |
np.savetxt( ) | 텍스트 파일에 numpy 배열 객체 저장 | 텍스트 |
- 다음과 같은 a, b 두개 배열 사용
a = np.random.randint(0, 10, (2, 3))
b = np.random.randint(0, 10, (2, 3))
pprint(a)
pprint(b)
type : <class 'numpy.ndarray'>
shape : (2, 3), demention : 2, dtype : int64
array's Data :
[[1 0 8]
[4 0 9]]
type : <class 'numpy.ndarray'>
shape : (2, 3), demention : 2, dtype : int64
array's Data :
[[6 2 4]
[1 5 3]]
배열 객체 저장
np.save 함수와 np.savez 함수를 이용하여 배열 객체를 파일로 저장
- np.save : 확장자(.npy)
- np.savez : 확장자(.npy)
- 배열 저장 파일은 바이너리 형태
np.save('./my_array1', a) # 파일 저장
np.savez('./my_array2', a, b) # 두개 파일 저장
np.load('./my_array1.npy') # 파일 조회
array([[1, 0, 8],
[4, 0, 9]])
npzfiles = np.load('./my_array2.npz') # 파일 로딩
npzfiles.files
['arr_0', 'arr_1']
npzfiles['arr_0']
array([[1, 0, 8],
[4, 0, 9]])
npzfiles['arr_1']
array([[6, 2, 4],
[1, 5, 3]])
텍스트 파일 로딩
텍스트 파일을 np.loadtxt 로 로딩할 수 있다.
-
np.loadtxt(fname, dtype=<class’float’>, comments=’#’, delimeter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndimn=0)
- fname : 파일명
- commeonts : comment 시작 부호
- delimiter : 구분자
- skiprows : 제외 라인 수(header 제거용)
np.loadtxt('./simple.csv')
array([[1., 2., 3.],
[4., 5., 6.]])
np.loadtxt('./simple.csv', dtype=np.int)
<ipython-input-72-bdfdd9e740a7>:1: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
np.loadtxt('./simple.csv', dtype=np.int)
array([[1, 2, 3],
[4, 5, 6]])
문자열을 포함하는 텍스트 파일 로딩
- president_height.csv 파일은 숫자와 문자를 모두 포함하는 데이터 파일이다.
- dtype을 이용하여 컬럼 타입을 지정하여 로딩한다.
- delimiter와 skiprows를 이용하여 구분자와 무시해야 할 라인을 지정한다.
data = np.loadtxt('./president_height.csv', delimiter=',', skiprows=1,
dtype={
'names': ('order','name','height'),
'formats':('i','S20','f')
})
data[:3]
array([(1, b'George Washington', 189.), (2, b'John Adams', 170.),
(3, b'Tomas Jefferson', 189.)],
dtype=[('order', '<i4'), ('name', 'S20'), ('height', '<f4')])
data = np.random.random((3, 4)) # 데모 데이터 생성
pprint(data)
type : <class 'numpy.ndarray'>
shape : (3, 4), demention : 2, dtype : float64
array's Data :
[[0.27407375 0.43170418 0.94002982 0.81764938]
[0.33611195 0.17541045 0.37283205 0.00568851]
[0.25242635 0.79566251 0.01525497 0.59884338]]
np.savetxt('./saved.csv', data, delimiter=',') # 텍스트 파일로 저장
np.loadtxt('./saved.csv', delimiter=',') # 파일 로딩
array([[0.27407375, 0.43170418, 0.94002982, 0.81764938],
[0.33611195, 0.17541045, 0.37283205, 0.00568851],
[0.25242635, 0.79566251, 0.01525497, 0.59884338]])
# 데이터 파일 로딩 실패
data = np.loadtxt('./dust.csv', delimiter=',', skiprows=1,
dtype={
'names': ('지역','지역명','도로명'),
'formats':('S20','S20','S20')
})
data[2:]
File "<ipython-input-113-9d9c851be0f6>", line 6
})
^
SyntaxError: positional argument follows keyword argument
import pandas as pd
# pandas 로 데이터파일 로딩
df = pd.read_csv('./pet1.csv', encoding='utf-8')
df
시도명 | 시군구명 | 구청명 | 법정동명 | 등록품종수 | 등록개체수 | 소유자수 | 관리부서명 | 관리부서연락처 | 데이터기준일자 | |
---|---|---|---|---|---|---|---|---|---|---|
0 | 경기도 | 수원시 | 권선구 | 탑동 | 67 | 1343 | 998 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
1 | 경기도 | 수원시 | 권선구 | 평동 | 26 | 127 | 102 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
2 | 경기도 | 수원시 | 권선구 | 고색동 | 49 | 924 | 697 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
3 | 경기도 | 수원시 | 권선구 | 구운동 | 61 | 1373 | 1065 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
4 | 경기도 | 수원시 | 권선구 | 권선동 | 87 | 4547 | 3483 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
5 | 경기도 | 수원시 | 권선구 | 금곡동 | 62 | 1972 | 1522 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
6 | 경기도 | 수원시 | 권선구 | 당수동 | 34 | 389 | 303 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
7 | 경기도 | 수원시 | 권선구 | 서둔동 | 56 | 934 | 664 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
8 | 경기도 | 수원시 | 권선구 | 세류동 | 87 | 3366 | 2474 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
9 | 경기도 | 수원시 | 권선구 | 입북동 | 31 | 284 | 229 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
10 | 경기도 | 수원시 | 권선구 | 장지동 | 4 | 10 | 10 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
11 | 경기도 | 수원시 | 권선구 | 평리동 | 1 | 1 | 1 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
12 | 경기도 | 수원시 | 권선구 | 곡반정동 | 62 | 1459 | 1027 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
13 | 경기도 | 수원시 | 권선구 | 오목천동 | 53 | 982 | 740 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
14 | 경기도 | 수원시 | 권선구 | 호매실동 | 59 | 1636 | 1254 | 권선구 경제교통과 | 031-228-6373 | 2020/10/06 |
15 | 경기도 | 수원시 | 영통구 | 신동 | 35 | 246 | 188 | 영통구 경제교통과 | 031-228-8882 | 2020/10/06 |
16 | 경기도 | 수원시 | 영통구 | 하동 | 59 | 1252 | 951 | 영통구 경제교통과 | 031-228-8882 | 2020/10/06 |
17 | 경기도 | 수원시 | 영통구 | 망포동 | 60 | 2242 | 1825 | 영통구 경제교통과 | 031-228-8882 | 2020/10/06 |
18 | 경기도 | 수원시 | 영통구 | 매탄동 | 85 | 4761 | 3764 | 영통구 경제교통과 | 031-228-8882 | 2020/10/06 |
19 | 경기도 | 수원시 | 영통구 | 영통동 | 81 | 3765 | 3115 | 영통구 경제교통과 | 031-228-8882 | 2020/10/06 |
20 | 경기도 | 수원시 | 영통구 | 원천동 | 56 | 1338 | 1025 | 영통구 경제교통과 | 031-228-8882 | 2020/10/06 |
21 | 경기도 | 수원시 | 영통구 | 이의동 | 72 | 2136 | 1664 | 영통구 경제교통과 | 031-228-8882 | 2020/10/06 |
22 | 경기도 | 수원시 | 장안구 | 송죽동 | 53 | 1222 | 954 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
23 | 경기도 | 수원시 | 장안구 | 연무동 | 58 | 1106 | 816 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
24 | 경기도 | 수원시 | 장안구 | 영화동 | 65 | 1384 | 989 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
25 | 경기도 | 수원시 | 장안구 | 율전동 | 53 | 1178 | 951 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
26 | 경기도 | 수원시 | 장안구 | 이목동 | 45 | 311 | 213 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
27 | 경기도 | 수원시 | 장안구 | 정자동 | 82 | 4205 | 3324 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
28 | 경기도 | 수원시 | 장안구 | 조원동 | 69 | 2835 | 2213 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
29 | 경기도 | 수원시 | 장안구 | 천천동 | 49 | 1242 | 1035 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
30 | 경기도 | 수원시 | 장안구 | 파장동 | 52 | 1117 | 885 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
31 | 경기도 | 수원시 | 장안구 | 상광교동 | 4 | 6 | 4 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
32 | 경기도 | 수원시 | 장안구 | 하광교동 | 13 | 22 | 15 | 장안구 경제교통과 | 031-228-5384 | 2020/10/06 |
33 | 경기도 | 수원시 | 팔달구 | 교동 | 36 | 178 | 113 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
34 | 경기도 | 수원시 | 팔달구 | 영동 | 13 | 35 | 24 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
35 | 경기도 | 수원시 | 팔달구 | 중동 | 6 | 26 | 17 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
36 | 경기도 | 수원시 | 팔달구 | 지동 | 61 | 986 | 700 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
37 | 경기도 | 수원시 | 팔달구 | 고등동 | 48 | 688 | 515 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
38 | 경기도 | 수원시 | 팔달구 | 구천동 | 16 | 59 | 42 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
39 | 경기도 | 수원시 | 팔달구 | 남수동 | 27 | 94 | 64 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
40 | 경기도 | 수원시 | 팔달구 | 남창동 | 26 | 96 | 70 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
41 | 경기도 | 수원시 | 팔달구 | 매교동 | 41 | 364 | 257 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
42 | 경기도 | 수원시 | 팔달구 | 매향동 | 20 | 72 | 55 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
43 | 경기도 | 수원시 | 팔달구 | 북수동 | 29 | 115 | 78 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
44 | 경기도 | 수원시 | 팔달구 | 신풍동 | 31 | 121 | 85 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
45 | 경기도 | 수원시 | 팔달구 | 우만동 | 68 | 2061 | 1572 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
46 | 경기도 | 수원시 | 팔달구 | 인계동 | 73 | 2924 | 2154 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
47 | 경기도 | 수원시 | 팔달구 | 장안동 | 20 | 70 | 55 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
48 | 경기도 | 수원시 | 팔달구 | 화서동 | 64 | 2609 | 2056 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
49 | 경기도 | 수원시 | 팔달구 | 매산로1가 | 29 | 157 | 90 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
50 | 경기도 | 수원시 | 팔달구 | 매산로2가 | 35 | 344 | 262 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
51 | 경기도 | 수원시 | 팔달구 | 매산로3가 | 37 | 231 | 164 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
52 | 경기도 | 수원시 | 팔달구 | 팔달로1가 | 13 | 25 | 16 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
53 | 경기도 | 수원시 | 팔달구 | 팔달로2가 | 19 | 46 | 31 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
54 | 경기도 | 수원시 | 팔달구 | 팔달로3가 | 13 | 33 | 23 | 팔달구 경제교통과 | 031-228-7355 | 2020/10/06 |
arr = np.random.random((5, 2, 3))
type(arr)
numpy.ndarray
arr.shape
(5, 2, 3)
len(arr)
5
arr.ndim
3
arr.size
30
arr.dtype
dtype('float64')
arr.dtype.name
'float64'
arr.astype(np.int)
<ipython-input-127-d877ecd8ec94>:1: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
arr.astype(np.int)
array([[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]]])
arr.astype(np.float)
<ipython-input-128-fb487a07ef9c>:1: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
arr.astype(np.float)
array([[[0.5928054 , 0.62994188, 0.14260031],
[0.9338413 , 0.94637988, 0.60229666]],
[[0.38776628, 0.363188 , 0.20434528],
[0.27676506, 0.24653588, 0.173608 ]],
[[0.96660969, 0.9570126 , 0.59797368],
[0.73130075, 0.34038522, 0.0920556 ]],
[[0.46349802, 0.50869889, 0.08846017],
[0.52803522, 0.99215804, 0.39503593]],
[[0.33559644, 0.80545054, 0.75434899],
[0.31306644, 0.63403668, 0.54040458]]])
a = np.arange(1, 10).reshape(3, 3)
pprint(a)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : int64
array's Data :
[[1 2 3]
[4 5 6]
[7 8 9]]
b = np.arange(9, 0, -1).reshape(3, 3)
pprint(b)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : int64
array's Data :
[[9 8 7]
[6 5 4]
[3 2 1]]
a-b
array([[-8, -6, -4],
[-2, 0, 2],
[ 4, 6, 8]])
np.subtract(a,b)
array([[-8, -6, -4],
[-2, 0, 2],
[ 4, 6, 8]])
a+b
array([[10, 10, 10],
[10, 10, 10],
[10, 10, 10]])
np.add(a,b)
array([[10, 10, 10],
[10, 10, 10],
[10, 10, 10]])
a/b
array([[0.11111111, 0.25 , 0.42857143],
[0.66666667, 1. , 1.5 ],
[2.33333333, 4. , 9. ]])
np.divide(a,b)
array([[0.11111111, 0.25 , 0.42857143],
[0.66666667, 1. , 1.5 ],
[2.33333333, 4. , 9. ]])
a*b
array([[ 9, 16, 21],
[24, 25, 24],
[21, 16, 9]])
np.multiply(a,b)
array([[ 9, 16, 21],
[24, 25, 24],
[21, 16, 9]])
np.exp(b)
array([[8.10308393e+03, 2.98095799e+03, 1.09663316e+03],
[4.03428793e+02, 1.48413159e+02, 5.45981500e+01],
[2.00855369e+01, 7.38905610e+00, 2.71828183e+00]])
np.sqrt(a)
array([[1. , 1.41421356, 1.73205081],
[2. , 2.23606798, 2.44948974],
[2.64575131, 2.82842712, 3. ]])
np.sin(a)
array([[ 1.55740772, -2.18503986, -0.14254654],
[ 1.15782128, -3.38051501, -0.29100619],
[ 0.87144798, -6.79971146, -0.45231566]])
np.cos(a)
array([[ 0.54030231, -0.41614684, -0.9899925 ],
[-0.65364362, 0.28366219, 0.96017029],
[ 0.75390225, -0.14550003, -0.91113026]])
np.tan(a)
array([[ 1.55740772, -2.18503986, -0.14254654],
[ 1.15782128, -3.38051501, -0.29100619],
[ 0.87144798, -6.79971146, -0.45231566]])
np.log(a)
array([[0. , 0.69314718, 1.09861229],
[1.38629436, 1.60943791, 1.79175947],
[1.94591015, 2.07944154, 2.19722458]])
np.dot(a, b)
array([[ 30, 24, 18],
[ 84, 69, 54],
[138, 114, 90]])
a==b
array([[False, False, False],
[False, True, False],
[False, False, False]])
a>b
array([[False, False, False],
[False, False, True],
[ True, True, True]])
np.array_equal(a,b) # 배열 전체 비교
False
a = np.arange(1, 10).reshape(3, 3)
pprint(a)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : int64
array's Data :
[[1 2 3]
[4 5 6]
[7 8 9]]
a.sum(), np.sum(a)
(45, 45)
a.sum(axis=0), np.sum(a, axis=0)
(array([12, 15, 18]), array([12, 15, 18]))
a.sum(axis=1), np.sum(a, axis=1)
(array([ 6, 15, 24]), array([ 6, 15, 24]))
a.max(), np.max(a)
(9, 9)
a.max(axis=0), np.max(a, axis=0)
(array([7, 8, 9]), array([7, 8, 9]))
a.max(axis=1), np.max(a,axis=1)
(array([3, 6, 9]), array([3, 6, 9]))
a.cumsum(), np.cumsum(a)
(array([ 1, 3, 6, 10, 15, 21, 28, 36, 45]),
array([ 1, 3, 6, 10, 15, 21, 28, 36, 45]))
a.cumsum(axis=0), np.cumsum(a, axis=0)
(array([[ 1, 2, 3],
[ 5, 7, 9],
[12, 15, 18]]),
array([[ 1, 2, 3],
[ 5, 7, 9],
[12, 15, 18]]))
a.cumsum(axis=1), np.cumsum(a, axis=1)
(array([[ 1, 3, 6],
[ 4, 9, 15],
[ 7, 15, 24]]),
array([[ 1, 3, 6],
[ 4, 9, 15],
[ 7, 15, 24]]))
a.mean(), np.mean(a)
(5.0, 5.0)
a.mean(axis=0), np.mean(a, axis=0)
(array([4., 5., 6.]), array([4., 5., 6.]))
a.mean(axis=1), np.mean(a, axis=1)
(array([2., 5., 8.]), array([2., 5., 8.]))
np.median(a)
5.0
np.median(a, axis=0)
array([4., 5., 6.])
np.median(a, axis=1)
array([2., 5., 8.])
a = np.arange(1, 25). reshape(4, 6)
pprint(a)
b = np.arange(25, 49). reshape(4, 6)
pprint(b)
type : <class 'numpy.ndarray'>
shape : (4, 6), demention : 2, dtype : int64
array's Data :
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]]
type : <class 'numpy.ndarray'>
shape : (4, 6), demention : 2, dtype : int64
array's Data :
[[25 26 27 28 29 30]
[31 32 33 34 35 36]
[37 38 39 40 41 42]
[43 44 45 46 47 48]]
a+b
array([[26, 28, 30, 32, 34, 36],
[38, 40, 42, 44, 46, 48],
[50, 52, 54, 56, 58, 60],
[62, 64, 66, 68, 70, 72]])
a = np.arange(1, 25).reshape(4, 6)
pprint(a)
type : <class 'numpy.ndarray'>
shape : (4, 6), demention : 2, dtype : int64
array's Data :
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]]
a+100
array([[101, 102, 103, 104, 105, 106],
[107, 108, 109, 110, 111, 112],
[113, 114, 115, 116, 117, 118],
[119, 120, 121, 122, 123, 124]])
a = np.arange(5).reshape((1, 5))
pprint(a)
b = np.arange(5).reshape((5, 1))
pprint(b)
type : <class 'numpy.ndarray'>
shape : (1, 5), demention : 2, dtype : int64
array's Data :
[[0 1 2 3 4]]
type : <class 'numpy.ndarray'>
shape : (5, 1), demention : 2, dtype : int64
array's Data :
[[0]
[1]
[2]
[3]
[4]]
a+b
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
a = np.arange(10000000)
result = 0
%%time
for v in a:
result += v
CPU times: user 1.29 s, sys: 4.47 ms, total: 1.29 s
Wall time: 1.29 s
result
49999995000000
a = np.random.randint(0, 9, (3, 3))
pprint(a)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : int64
array's Data :
[[1 3 1]
[4 8 8]
[2 2 7]]
copied_a1 = np.copy(a)
pprint(copied_a1)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : int64
array's Data :
[[1 3 1]
[4 8 8]
[2 2 7]]
copied_a1[:, 0]=0
pprint(copied_a1)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : int64
array's Data :
[[0 3 1]
[0 8 8]
[0 2 7]]
unsorted_arr = np.random.random((3,3))
pprint(unsorted_arr)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : float64
array's Data :
[[0.01742254 0.05096687 0.43507174]
[0.97684387 0.09378331 0.5515195 ]
[0.64310314 0.44025463 0.78887382]]
unsorted_arr1 = unsorted_arr.copy()
unsorted_arr2 = unsorted_arr.copy()
unsorted_arr3 = unsorted_arr.copy()
unsorted_arr.sort()
pprint(unsorted_arr1)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : float64
array's Data :
[[0.01742254 0.05096687 0.43507174]
[0.97684387 0.09378331 0.5515195 ]
[0.64310314 0.44025463 0.78887382]]
unsorted_arr2.sort(axis=0)
pprint(unsorted_arr2)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : float64
array's Data :
[[0.01742254 0.05096687 0.43507174]
[0.64310314 0.09378331 0.5515195 ]
[0.97684387 0.44025463 0.78887382]]
unsorted_arr3.sort(axis=1)
pprint(unsorted_arr3)
type : <class 'numpy.ndarray'>
shape : (3, 3), demention : 2, dtype : float64
array's Data :
[[0.01742254 0.05096687 0.43507174]
[0.09378331 0.5515195 0.97684387]
[0.44025463 0.64310314 0.78887382]]
a0 = np.arange(24)
pprint(a0)
a1 = np.arange(24).reshape((4, 6))
pprint(a1)
a2 = np.arange(24).reshape((2, 4, 3))
pprint(a2)
type : <class 'numpy.ndarray'>
shape : (24,), demention : 1, dtype : int64
array's 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 : (4, 6), demention : 2, dtype : int64
array's 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), demention : 3, dtype : int64
array's 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]]]
a0[5]
5
a0[5] = 100000
pprint(a0)
type : <class 'numpy.ndarray'>
shape : (24,), demention : 1, dtype : int64
array's Data :
[ 0 1 2 3 4 100000 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23]
a1[0,1]=10000
pprint(a1)
type : <class 'numpy.ndarray'>
shape : (4, 6), demention : 2, dtype : int64
array's Data :
[[ 0 10000 2 3 4 5]
[ 6 7 8 9 10 11]
[ 12 13 14 15 16 17]
[ 18 19 20 21 22 23]]
a2[1, 0, 1] = 10000
pprint(a2)
type : <class 'numpy.ndarray'>
shape : (2, 4, 3), demention : 3, dtype : int64
array's Data :
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[ 12 10000 14]
[ 15 16 17]
[ 18 19 20]
[ 21 22 23]]]
a1 = np.arange(1, 25).reshape((4, 6))
pprint(a1)
type : <class 'numpy.ndarray'>
shape : (4, 6), demention : 2, dtype : int64
array's Data :
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]]
a1[1:3, 1:5]
array([[ 8, 9, 10, 11],
[14, 15, 16, 17]])
a1[1:-1, 1:-1]
array([[ 8, 9, 10, 11],
[14, 15, 16, 17]])
pprint(a1)
type : <class 'numpy.ndarray'>
shape : (4, 6), demention : 2, dtype : int64
array's Data :
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]]
slide_arr = a1[1:3, 1:5]
pprint(slide_arr)
type : <class 'numpy.ndarray'>
shape : (2, 4), demention : 2, dtype : int64
array's Data :
[[ 8 9 10 11]
[14 15 16 17]]
slide_arr[:, 1:3]
pprint(slide_arr)
type : <class 'numpy.ndarray'>
shape : (2, 4), demention : 2, dtype : int64
array's Data :
[[ 8 9 10 11]
[14 15 16 17]]
slide_arr[:, 1:3] = 99999
pprint(slide_arr)
type : <class 'numpy.ndarray'>
shape : (2, 4), demention : 2, dtype : int64
array's Data :
[[ 8 99999 99999 11]
[ 14 99999 99999 17]]
pprint(a1)
type : <class 'numpy.ndarray'>
shape : (4, 6), demention : 2, dtype : int64
array's Data :
[[ 1 2 3 4 5 6]
[ 7 8 99999 99999 11 12]
[ 13 14 99999 99999 17 18]
[ 19 20 21 22 23 24]]