열렬히.뛰기

여러가지 계산

Language > 프로그래밍 언어 > Python > 파이썬 : 데이터 핸들링 > 여러가지 계산

넘파이와 계산기능

데이터 연산

python
arr2+200
>>> Out[9]: array([[200, 201, 202],
						       [203, 204, 205],
						       [206, 207, 208]])

arr2-100
>>> Out[10]: array([[-100,  -99,  -98],
							      [ -97,  -96,  -95],
								    [ -94,  -93,  -92]])
			
arr2//100
>>> Out[11]: array([[0, 0, 0],
							      [0, 0, 0],
						        [0, 0, 0]], dtype=int32)


arr2/2
Out[12]: 
array([[0. , 0.5, 1. ],
       [1.5, 2. , 2.5],
       [3. , 3.5, 4. ]])

형식변환

python
#%% astype()를 이용한 데이터형식 변환
str_a1 = np.array(['1.4', '0.123', '5.123', '9', '8'])
str_a1.dtype
num_a1 = str_a1.astype(float)
print(num_a1)
>>> [1.4   0.123 5.123 9.    8.   ]

num_a2 = num_a1.astype(int)
print(num_a2)
>>> [1 0 5 9 8]

# 간결하게
str_a1.astype(float).astype(int)

str_a2 = np.array(['1', '2', '3', '4', '5'])
str_a2.dtype
num_a2 = str_a2.astype(int)
num_a2

연산 메소드 1

python
#%% 메소드1: linspace()
"""linspace: float가 기본."""
"""따라서 .astype()으로 바꿔줘야 함."""
A = np.linspace(1, 9, 9)
A.astype(int)
np.linspace(1, 100, 21).astype(int)

#%% 메소드2 : ones(), zeros()
""" 0 또는 1들로 가득찬 배열 생성 """
""" 역시 default = float """

np.ones(5)
np.ones(10).astype(int)
np.zeros(10)

#%% 메소드3: .where()
"""값으로 위치 찾기"""
arr1 = np.linspace(1, 10)
arr2 = np.linspace(np.pi, 200, 12).astype(int)
np.where(arr1==1)
np.where(arr2==3)

연산 메소드 2

python
#%% 메소드4: eye(n)
# 단위행렬 생성
np.eye(10)

#%% 메소드5: diag(n)
# 대각행렬 생성. n에는 배열 들어감.
np.diag([i for i in range(1, 10)])

통계연산

python
A = np.linspace(1, 101)
[A.sum(), A.min(), A.max(), A.mean()]
A.cumsum().astype(int)

B = np.arange(1, 10).reshape(3,3)
B.cumsum()
B.cumprod()

행렬연산

python
A = np.array([[1,0,3], [2,4,5], [3,10,9]])
B = np.array([[10,2,-1], [-2,0,15], [7,-8,15]])

A.dot(B)
A.transpose()
np.transpose(A)
np.linalg.inv(A)
np.linalg.det(A)