Silver bullet
기초 Numpy & Pandas 본문
1. Numpy Recap
1-1) np.ndarray 만들기
import numpy as np
v1 = np.array([1, 2, 3, 4]) # 배열(Array)
v1
v1.dtype # d(ata)-type
v1.shape # '모양'을 영어로?
sample_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
sample_matrix
sample_matrix.shape
# print(sample_matrix[0])
# print(sample_matrix[0, 0])
# print(sample_matrix[0, 2])
# print(sample_matrix[0:2, 1:3])
print(sample_matrix[ : , 2])
ML/DL 할 때는 2차원 이상을 행렬을 넣어주어야 한다.
1-2) np.arange & np.reshape
v1 = np.arange(5) # 'a'rray of 'range'
v1 # array([0, 1, 2, 3, 4])
v2 = np.arange(1, 10, 2)
v2 # array([1, 3, 5, 7, 9])
# Brodcastiong
v4 = np.arange(1, 10, 2) ** 2 # 제곱 연산자가 무엇이었죠?
v4 # array([ 1, 9, 25, 49, 81])
[1, 3, 5, 7, 9] * 2
# [1, 3, 5, 7, 9, 1, 3, 5, 7, 9]
v1 = np.arange(12)
v1 # array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
v2 = v1.reshape(4, -1) # -1은 알아서 열 계산해서 바꿔달라는 뜻
v2
# array([[ 0, 1, 2],
# [ 3, 4, 5],
# [ 6, 7, 8],
# [ 9, 10, 11]])
# 행 단위가 아닌 열 단위부터 먼저 채우라는 뜻
v3 = v1.reshape(2, 6, order='F') # C & Fortran
v3
# array([[ 0, 2, 4, 6, 8, 10],
# [ 1, 3, 5, 7, 9, 11]])
# 메서드 체이닝 (method-chaining)
v1 = np.arange(12).reshape(2, 6)
v1
# array([[ 0, 1, 2, 3, 4, 5],
# [ 6, 7, 8, 9, 10, 11]])
1-3) np.ndarray 의 사칙연산
v1 = np.arange(1, 5).reshape(2, 2)
v1
# array([[1, 2],
# [3, 4]])
np.max(v1, axis = 0)
# array([3, 4])
np.min(v1)
# 1
np.mean(v1)
# 2.5
np.std(v1)
# 1.118033988749895
1-4) 행렬 간의 사칙연산
v1
# array([[1, 2],
# [3, 4]])
np.add(v1, v1) # 더하기 (element-wise add)
# array([[2, 4],
# [6, 8]])
np.subtract(v1, v1) # 빼기 (element-wise subtract)
# array([[0, 0],
# [0, 0]])
np.multiply(v1, v1) # 곱하기 (element-wise multiply)
# array([[ 1, 4],
# [ 9, 16]])
np.dot(v1, v1) # 행렬곱 == 점곱 (dot-product)
# array([[ 7, 10],
# [15, 22]])
2. Pandas Recap
import pandas as pd
# Series : Key(index) 값이 있는 리스트
a = pd.Series([1, 3, 5, 7])
a.values
# array([1, 3, 5, 7], dtype=int64)
a.index
# RangeIndex(start=0, stop=4, step=1)
a2 = pd.Series([1, 3, 5, 7], index=['a', 'b', 'c', 'd'])
a2
# a 1
# b 3
# c 5
# d 7
# dtype: int64
# DataFrame에서 하나의 Cell에 해당하는 값을 얻어내는 4가지 방법
df['amount'][0] # 열에 접근 후 Series의 index로 접근
df.loc[0]['amount'] # 행에 접근 후 Series의 index로 접근
df.loc[0, 'amount'] # 행 이름과 열 이름을 지정하여 접근 (loc 활용)
df.at[0, 'amount'] # 행 이름과 열 이름을 지정하여 접근 (at 활용) <- 제일 추천 방법
df.iloc[0, 7] # indexed-location 기반으로 index number 기준 행 & 열 지정하여 접근
df.insert(8, 'total_payment_', df['amount'] * df['count']) # index 기준으로 8번 열에 새로운 열을 "삽입"
df.head()
del df['total_payment']
del df['total_payment_']
df['edu'].value_counts() # 출현 횟수
from collections import Counter
counted = Counter(df['edu'].values)
pd.Series(data=counted.values(), index=counted.keys())
def num_to_character(data):
if data == 1:
return 'male'
else:
return 'female'
df['gender_2'] = df['gender'].apply(num_to_character) # 적용하다
# df['gender_2'] = df['gender'].apply(lambda x : 'male' if x == 1 else 'female')
df.head()'AI > AI' 카테고리의 다른 글
| 교차 검정 (p-value) (0) | 2024.07.04 |
|---|---|
| 데이터 탐색과 기술 통계 분석 (0) | 2024.07.04 |
| 한글 텍스트 데이터 전처리 (0) | 2024.07.02 |
| TF-IDF & Cosine similarity 이론 (0) | 2024.07.02 |
| 품사별 토큰 추출 & 등장횟수 시각화, 정규 표현식 (0) | 2024.07.01 |