본문 바로가기
Python_Wiki/Python_Library

Pandas EDA 기초 및 함수

by yj-data 2025. 5. 20.

#eda의 기본 과정(탐색적 데이터 분석) - 미국 통계학자가 제안한 방법론. 기존 통계학의 방법을 따르다가는 데이터 본래의 정보를 파악하기 어려우므로, 본연의 데이터 탐색에 집중하자는 방법론.
#1. 데이터의 출처와 주제에 대해 이해
#2. 데이터의 크기 확인
#3. 데이터의 구성요소의 속성 확인

import pandas as pd
doc = pd.read_csv(
    "COVID-19-master/csse_covid_19_data/csse_covid_19_daily_reports/04-01-2020.csv",
    encoding='utf-8-sig'
)

#reading excel using Pandas
pd.read_excel('filename.xlsx') #reads data from the first sheet
pd.read_excel('filename.xlsx', sheet_name = 'sheetname') #read data from the particular sheet

 

 

#2. 데이터의 크기 확인

#what you do after you read data with pandas
#1) check the partial data
doc.head() #doc.head(n=10) means checking 10, default value is 5
doc.tail()
doc[인덱스:인덱스] #일반적인 인덱싱 가능. 인덱스 넘버로 필요한 부분의 데이터를 뽑아오자


#2) check more aspects of data
doc.shape #(행,열)크기 확인, no () at the end
doc.info() #데이터에 대한 전반적인 정보 제공(행과 열의 크기, 컬럼명, 컬럼별 결측치, 컬럼별 데이터 타입)
doc.type() #데이터타입 확인
doc.dtypes #열의 타입을 시리즈로 반환 (특정 타입을 가진 컬럼만 추출: df.select_dtypes('object'))
           # int64 등이 타입으로 확인되나, ' '안에는 int로 넣어도됨
doc.astype() #타입변경(예, df['PassengerId'].astype(str))
             #int타입으로 바꾸고, 결측치 표시하는법: 먼저 결측치를 -1로 바꾸고, int로 바꾼다음, -1을 결측치로 다시 치환
             #df1['Age'] = df1['Age'].fillna(-1).astype(int).replace(-1, np.nan)



#3) more ways to analyze data
doc.size #check the size
doc.count() #checking the size without null data
doc.unique() #return only the unique values
doc.value_counts() #count the data without null data, return the number of each value 
    #.value_counts(normalize=False, sort=True, ascending=True)
    #normalize true인경우, 값을 비율로 나타냄
    #df.value_counts에는 (subset=None)이 인자로 추가될 수있음. .value_counts(['col','col2']) 가능
len(doc.unique()) #count the amount of unique data
doc.groupby()
     #example1
     survive = titanic.groupby("Sex")["Survived"].mean()
     (survive * 100).head()
     #example2
     titanic.groupby(["Sex", "Pclass"])[["Age", "Fare"]].mean()
doc.groupby().함수
    .count() #행의 개수, doc.groupby().count()
    .nunique() #행의 유니크한 개수
    .sum()  .mean()   .min()   .max()   .std()   .var()
    # 각 함수별로 여러 값을 보고싶은 경우 .aggregate()
    #example
    import numpy as np
    df.groupby(['Sex','Pclass'])[['Survived','Age','SibSp']].aggregate([np.mean, np.min, np.max])

.value_counts() : 결과 비교 / 조건을 두개 넣으면 두 조건의 모든 쌍으로 결과가 나옴
groupby 결과
groupby 결과2



 

#3. 데이터의 구성요소의 속성 확인

#1) 각 column 이해하기
doc.columns

#2) if attributes are int, find: mean, stdev, quartile, min/max
doc.describe() #count, mean, std, min, max, 25%/50%/75%

#3) correlation b/w attributes
doc.corr(numeric_only=True) #recently, there have been errors regarding including str columns, so add 'nume~~' after corr

#4) basic statistics
#min max mean median std var quantile 함수에서는 ()안에 numeric_only=True를 넣어서 숫자형 데이터만 추출할 수 있음
doc.mean()     #평균
doc.median()   #중앙값
doc.min()   #최소값
doc.max()   #최대값
doc.std()	#표준편차
doc.var()	#분산
doc.quantile()	#분위수 #doc.quantile(0.9, numeric_only=True) 처럼 숫자를 넣어서 자유자재로 분위수 추출 가능
doc.agg()      #여러개의 열에 다양한 함수를 적용
   #group객체.agg([함수1,함수2,...]) #모든 열에 여러 함수를 매핑
   #group객체.agg({"열1":함수1, "열2":함수2,...}) #각 열마다 다른 함수를 매핑

예시