저번주에 한달치/1주일치 회고를 빠뜨렸다. 아무래도 설날도 있었고 그만큼 좀 늘어졌던 것 같다. 단위 프로젝트를 다시 해보겠다는
다짐도 물 건너갔다. 이번주(?)에 배운 것 중 잘 모르는 것들 위주로, 대략적으로 정리해보겠다.
- pandas
- 데이터 시각화 (matplotlib, seaborn), EDA
- numpy
- data encoding, scaling
1. pandas
- scalar/0/ > vector/1/series > matrix/2/DataFrame
- slicing: vector[:3]
- df.to_dict('records'), df.to_json(orient='records') => list(list of dict())
- iris[iris[col]>5.0].iloc[:,:-1].median(axis=1) : 조건문, 뒤에서부터 slicing,컬럼 축으로 통계 내기
- df[~cond] : Not 조건
- df.select_dtyps(include=[np.number,object]).head() : dtype 가져오기
- df.isnull().sum(axis=0): 컬럼 안의 데이터 합쳐서 결측치 찾기
- df.[col].value_counts() : 카테고리별 개수
- df['gender'] = df['sex'].map({'male':0, 'female':1}) : 명목변수를 수치로 바꾸기
- df.apply(lambda data:data.mean(),axis=0) : 행 단위로 평균내주기
- df.picot_table(index=col1,columns=col2, values= target_col, aggfunc=['mean','median']) : col1,col2를 기준으로 col3 보기
- groups=df.groupby(col)
- groups.agg(['mean','median']) 그룹별 통계수치 보기
- groups.get_group(col)
- pd.merge(left_df, right_df, on=col,how='left') 차집합, outer은 합집합
- pd.concat([df1,s1],axis=1,ignore_index=True) : outer join, 중복 인덱스 피하기
- df.drop([col1,col2], axis=1, inplace=True) : 원본 데이터에서 col1,col2 drop
- df[date_col]=pd.to_datetime(df[date_col]) >> df[yr_col]=df[date_col].dt.year : 시점 변화시키기
2. 시각화, EDA
- 중요한건 데이터 타입에 따라 어떤 그래프를 쓸 줄 알아야 하는 지 알아야 한다.
- boxplot,선 그래프, 히스토그램 : 수치 데이터 / 막대 그래프 : 카테고리 데이터 / scatterplot, lineplot: 상관관계
- pivot_table의 시각화 버전
plt.figure(figsize=(12, 6))
plt.plot(df_comp_sum[df_comp_sum["항공사별(1)"] == "아시아나항공"]["년"],
df_comp_sum[df_comp_sum["항공사별(1)"] == "아시아나항공"]["화물 (톤)"],
label="아시아나항공")
plt.plot(df_comp_sum[df_comp_sum["항공사별(1)"] == "대한항공"]["년"],
df_comp_sum[df_comp_sum["항공사별(1)"] == "대한항공"]["화물 (톤)"],
label="대한항공")
plt.xlabel("년도")
plt.ylabel("화물 운송량 (톤)")
plt.legend()
plt.title("년도별 아시아나 항공과 대한항공의 화물 운송량 추이")
plt.show()
- 상관관계/왜도/첨도/교차분석
- crosstab, 교차분석: 두 개 이상의 범주형 변수를 빈도로 상관관계 분석
# Assuming df_num2 is already defined and contains your data
# Define the number of rows and columns for the subplot grid
n_rows = 1
n_cols = 3
# Create the subplot grid
fig, axes = plt.subplots(n_rows, n_cols, figsize=(15, 5)) # Adjust figsize as needed
# Flatten the axes array for easier iteration
axes = axes.flatten()
# Iterate through columns and plot on the corresponding subplot
for i, col in enumerate(df_num2.columns):
sns.histplot(df_num2[col], kde=True, ax=axes[i]) # Plot on the current subplot
skewness = round(df_num2[col].skew(), 2)
kurt = round(df_num2[col].kurt(), 2)
axes[i].set_title(f'{col},skew:{skewness},kurt:{kurt}') # Set title for each subplot
plt.tight_layout() # Adjust spacing between subplots
plt.show()
3. numpy
- 차원변환: arr[:,np.newaxis]/ arr.resize((row,col))/arr.reshape(row,-1) :원본유지/ arr.T / arr.ravel() : flattened
- dtype : arr.astype(np.float32) : dtype 널널하게 해서 오류 안나게 하기
- 조건 연산: arr[cond&cond2] / np.where(cond) / np.any(cond) / np.all(cond) / np.inf, np.nan/ np.isinf(arr), np.isnan(arr), np.isfinite(arr)
- slicing : arr[:,::-1] : 모든 행, 뒤에서부터 세기
- broadcasing: arr.shape 달라도 벡터 길이 동일시 작은 배열을 자동으로 큰 배열 크기에 맞춘다.
- 벡터 유사도: 각 벡터 크기 norm을 계산하여 (피타고라스 정리,L2 Norm) > 벡터2를 벡터1 기준으로 코사인 변환하여 같은 선상에 두고 >두 개의 벡터간의 유사도 비교
- 모델 loss는 벡터이며, 이걸 norm 또는 내적 연산하여 스칼라로 줄여서 볼 수 있다.
- np.random
- seed, rand, randint, randn, standard_normal, normal, random_sample, choice
4. encoding, scaling (preprocess)
- encoding: mean, label , one-hot : 대표 숫자값으로 인코딩
- scaling : standardscaler(평균,분산), minmaxscaler(최소,최대값 사이 범위), maxabsscaler(절대값 1이하), robustscaler (IQR 기준)
정리 해놓고 보니 겁나 뭐가 없다... 사실 이렇게 정리하는 것도 좋지만 코드를 쳐보는 게 더 좋긴한데... 여력이 없네 ㅠㅠ
그래도 이렇게라도 정리해야지
'개발공부 > SK Networks Family AI bootcamp 강의노트' 카테고리의 다른 글
18일차 [ 지도 학습 ] (0) | 2025.02.10 |
---|---|
17일차 [data encoding, scaling] (0) | 2025.02.07 |
16-17일차 [ 타이타닉 데이터 재분석 ] (0) | 2025.02.06 |
16일차 [ numpy 심화 ] (0) | 2025.02.06 |
16일차 [Bike sharing demand 데이터 분석/ 머신러닝 개요 / numpy 기초] (0) | 2025.02.06 |