Numpy

< numpy array의 특징 >
1. 모든 원소의 dtype이 같다.
2. 연산의 의미가 조금 다르다. (broadcasting)
3. 대용량 array인 경우에 for문을 직접 사용하는 것보다 내부적으로 정의된 연산을 사용하는게 더 빠르다.
4. 생성 후에 크기 변경이 불가능하다.

import numpy as np

data2 = [[1, 2],
         [3, 4]]
arr2 = np.array(data2) 
arr2.shape

np.arange(0, 10)
np.zeros(shape=(5, 3))
np.linspace(0, 1, 100) # [start, stop]에서 num개의 number를 균등한 구간으로 잘라서 원소를 생성.
np.random.randn(5, 3)  # 주어진 shape을 가지는 numpy array를 만들어주는데, 원소는 표준정규분포에서 sampling.

# shape은 가장 바깥 괄호부터 원소의 개수를 순차적으로 기록한 것으로 정의.
x = np.zeros(shape=(5, 3, 4))

# 224 x 224 크기의 3개(RGB) channel을 가지고 있는 이미지가 32개.
x = np.zeros(shape=(32, 3, 224, 224))

array 합치기

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# stacking vertically
np.vstack([arr1, arr2])
# stacking horizontally
np.hstack([arr1, arr2])

연산 : Universal Function

v1 = np.array((1, 2, 3))
v2 = np.array((4, 5, 6))

+, -, *, /, @(행렬곱 연산)

arr1 = np.array([1, 2, 3])
arr2 = np.array([[-1, -1, -1],
                 [1, 1, 1]])
            
arr1 * arr2

np.random.seed(42)   # set seed number
mat1 = np.random.randn(5, 3)
# .abs(), .square(), .astype('complex')


# linear algebra functions
vec = np.array([1, 2, 3])

# 1. norm
np.linalg.norm(vec)

# 2. eigenvalue
mat = np.array([[1, 0],
                [0, 1]])
np.linalg.eig(mat)


# axis=0 : 세로방향(=column방향), axis=1 : 가로방향(=row방향)
np.sum(mat2, axis=1)
np.mean(mat2, axis=0)
np.std(mat2, axis=1)
np.min(mat2)
np.max(mat2, axis=1)
# 최소값이 있는 Index
np.argmin(mat2, axis=1)
# 최대값이 있는 Index
np.argmax(mat2, axis=0)

Universal Function 기능을 통해 반복문을 사용한 것보다 훨씬 빠른 성능

Pandas

  • DataFrame은 2차원 테이블이고, 테이블의 한 줄(행/열)을 Series라고 합니다.
  • Series의 모임이 곧, DataFrame이 됩니다.
np.random.seed(42)
df = pd.DataFrame(data=np.random.randn(12, 4),
                  index=np.arange(12),
                  columns=['X1', 'X2', 'X3', 'X4'])

df.index
df.columns
df.values
df['X1']
df['X1'] + 2

Dataframe 기초 method

df.head()
df.tail()
df.info()
df.describe()
df.sort_values(by='X2', ascending=False)

Indexing

전체 데이터에서 원하는 일부의 데이터를 찾아오는 방법

df['X1']
df[0:3] # 0, 1, 2

# df에서 index value를 기준으로 indexing도 가능합니다. (여전히 row 단위)
df.loc[2]
df.loc[3, 'X4']
df.loc[[0, 1, 4, 5], 'X3'] 

mask = df['X3'] > 0   ## boolean mask
df[mask]

df.loc[df['X1'] < 1, 'X2']

df.iloc[1, 1]
df.iloc[[3, 4], [0, 1]]

여러 DataFrame 합치기

pd.concat([df1, df2, df3], axis=0)  # column을 기준으로 합침.
pd.concat([df1, df2.reset_index(drop=True), df3.reset_index(drop=True)], axis=1)  # index를 기준으로 합침.

# A inner join B  --> table A와 table B의 특정 column에서 겹치는 값들을 기준으로 두 테이블을 합치는 연산.
pd.merge(left=df1, right=df2, on='A', how='inner')

# df2 inner join df3 (column C)
pd.merge(df2, df3, on="C", how='inner')[['C', 'A_x', 'B_x', 'D_x', 'A_y', 'B_y', 'D_y']]

# left join : left table(df1)을 기준으로 right table(df2)에서 on에 대해서 겹치는 대상을 붙여줍니다. 겹치지 않는 데이터는 NaN(빈칸)으로 추가합니다.
pd.merge(df1, df2, on="A", how='left')

데이터 불러오기

titanic = pd.read_csv('./data/train.csv')
titanic

Pivot Table

  • pivot table이란 기존 테이블 구조를 특정 column을 기준으로 재구조화한 테이블을 말합니다.
  • 특정 column을 기준으로 pivot하기 때문에, 어떤 column에 어떤 연산을 하느냐에 따라서 만들어지는 결과가 바뀝니다.
  • 주로 어떤 column을 기준으로 데이터를 해석하고 싶을 때 사용합니다.
pd.pivot_table(data=titanic, index='Sex', values='Survived', aggfunc=['count', 'sum', 'mean'])
pd.pivot_table(data=titanic, index=['Sex', 'Pclass'], values='Survived', aggfunc=['mean']).plot(kind='bar')

Seaborn

데이터 시각화 라이브러리. matplotlib 기반, pandas 와 호환성 높음

Hisplot, Displot, Barplot, Countplot, Boxplot, Violinplot, Lineplot, Pointplot, Scatterplot, Pairplot, Heatmap(상관관계)

import matplotlib.pyplot as plt

plt.figure(figsize=(16, 4))
plt.title("Bill Length", fontsize=16, loc='left')
sns.histplot(data=data, x='bill_length_mm', bins=15, hue='species', multiple='stack', palette='Spectral')
plt.xlabel("Bill Length")
plt.ylabel('Number of Penguins')
plt.xlim(45, 60)

# penguin 데이터에 boxplot을 출력합니다.
sns.boxplot(data=data, x='species', y='body_mass_g')

sns.pairplot(data=data, hue='species')

# 각 feature간 상관관계를 파악하기 위해 Correlation matrix를 만듭니다.
corr = data.corr(numeric_only=True)
# penguin 데이터에 heatmap을 출력합니다.
sns.heatmap(data=corr, annot=True, fmt='.4f', cmap='Reds')
profile
인공지능관련 작업중

0개의 댓글