본문 바로가기
기본소양/CODE

1. Data Preprocess & EDA [4] CODE

by EXUPERY 2021. 1. 2.
반응형

1. 기본설정

# 패키지 및 폰트설정

!sudo apt-get install -y fonts-nanum
!sudo fc-cache -fv
!rm ~/.cache/matplotlib -rf
!pip3 install numpy
!pip3 install pandas

import pandas as pd
import numpy as np
import io 
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import warnings

plt.rc('font', family='NanumBarunGothic') 
mpl.rc('axes', unicode_minus=False)
warnings.filterwarnings("ignore")
%matplotlib inline
%config InlineBackend.figure_format='retina'
# 다운받고 로컬에서 업로드해서 불러오기

from google.colab import files
uploaded = files.upload()
df = pd.read_csv(io.BytesIO(uploaded['file1.csv']))

2. 데이터프레임으로 만들기

# 데이터 확인
df= pd.read_csv(url)
print(df.shape) # shape
print(df.info()) # info 
print(df.isnull().sum()) # 결측 값 수
print(df.sum()) # 합
# df.dropna(inplace=True) # 결측값제거하고 (필요시)
# df.isnull().sum() # 결측값없앤거 확인 (필요시)
# sheet별로 열어보기
df= pd.read_excel(url,"sheet이름") #  sheet name에 공백.

# 데이터 결측치 Na값을 0으로 대체하기 
df.fillna(0, inplace=True)

# 범위슬라이싱
df1 = df.loc[[22],:] # 22행 전체열

# index 설정하기
df.set_index('featre이름', inplace=True) # featre 열을 index로 지정한다.

# 데이타프레임 출력하기
df.to_csv('newfile.csv')

3. 데이터 다듬기

# 데이터를 불러오기
urlhead = '공통 url 헤드'
url_lists = ['파일1.csv','파일2.csv','파일3.csv']

# 데이터 필요한 형태로 다듬어 새로운 데이터프레임으로 만드는 함수 만들기
def df_load(url):
    df = pd.read_csv(urlhead + url).T # 1.데이터를 transpose
    new_header = df.iloc[0] # 2. column의 이름을 변경 및 설정
    df = df[1:] # 3.데이터의 일부 선택 (인덱스 1 부터 끝까지)
    df.columns = new_header
    df = df[["feature1",'feature3','feature5']] # 4. 필요한 feature만 붙여서 새로운 데이터프레임
    return df[-1:] 5. 마지막으로부터 1번째부터 :끝까지 반환

#함수를 이용해서 새로운 데이터프레임만들기
df1 = df_load(url_lists[0])
df2 = df_load(url_lists[1])
df3 = df_load(url_lists[2])

# 합치기
df_1= pd.concat([df1, df2, df3])

# 인덱스 리셋하기 
df_1 = df_1.reset_index() # 다른 새로운 데이터프레임과 index를 갖게해서 합치기 위함

# column 이름 설정하기
df = df.rename(columns = {'변경전' : '변경후'})
# replace를 이용한 숫자로만드는 함수 만들기( 컴마 빼버리기 )
def toInt(string): 
    return int(string.replace(',',''))
    
# replace를 이용하지않은 숫자로만드는 함수 만들기( 컴마 빼버리기 )
def toInt(string):
  numeric_filter = filter(str.isdigit, string)
  string = "".join(numeric_filter)
  return int(string)
  
# df에 apply하기
df['feature1'] = df['feature1'].apply(toInt)
df['feature2'] = df['feature2'].apply(toInt)
df['feature3'] = df['feature2'] / df['feature1'] # feature1과 feature2의 연산으로 새로운 feature3 생성 (df에 맨오른쪽으로 붙음)
print(df['feature3'])
datatype을 숫자형으로 바꾸기
df['feature1'] = pd.to_numeric(df['feature1'])
# 특정 행,열 부분을 Na로 대체하기
df.loc[행,열] = np.nan # 특정 행,열값에 결측값넣고
df_ktng.head()

# 헤더를 리스트로 만들기
headers = df.colums

# 리스트에 있는 헤더들을 이용하여 모든 열의 nan에 각 열의 평균 넣기  
for i in headers :
  if i == '분기': # 분기는 '/'가 있으므로 예외사항 이므로 먼저 패스
    pass
  else :
    df[i]=df[i].fillna(df[i].mean())

# 각 행에대해 조건에 따른 값이 나오게 하고, 이를 새로운 feature로 생성하기
for i in range(0,len(df.index)) :
  condition = '조건넣기'
  if condition > 1 :
    df_ktng.loc[i,"Relative Perfomance"] = '1등급'
  elif condition > 0 :  
    df_ktng.loc[i,"Relative Perfomance"] = '2등급'
  else : 
    df_ktng.loc[i,"Relative Perfomance"] = '폐기등급'
# Tidy 형태로 만들기
df = df_reset_index()
df_tidy = df.melt(id_vars= 'index variables', value_vars=["A",'B','C'])
  #id_vars의 변수 A,B,C에 따른 값Value 
df_tidy = df_tidy.sort_values('index variables') # 정렬
df_tidy
# 2자리까지만 보이게 셋팅
pd.options.display.float_format = "{:,.2f}".format
# Merge
df1.merge(df2, how='') # how = left, right, outer, inner
# GroupFeature이라는 컬럼으로 Grouping을하고 각 feature별로 평균을 냄
df1 = df.groupby('GroupFeature').feature1.mean()
df2 = df.groupby('GroupFeature').feature2.mean()
df3 = df.groupby('GroupFeature').feature3.mean()
df = pd.concat([df1,df2,df3], axis = 1)
df

4. 시각화하기

# 팔레트 색상 가져오기
qualitative_colors = sns.color_palette("Pastel1", 10)
qualitative_colors = sns.color_palette("Set3", 10)
sns.set_palette(qualitative_colors)
#Matplotlib

#barplot으로 시각화하기
df1.plot.bar() 

#pairplot
sns.pairplot(data = df)
plot.show()

#시각화하기
plt.show(df.iloc[22].plot.bar()) # iloc는 인덱스넘버로 찾는거고
plt.show(df.loc["ROA(%)"].plot.bar()) # loc는 그냥 아예 위치로 찾는거

# plot그리고 시각화하기 (Pandas)
df.plot(kind='bar',figsize =[10,6], fontsize = 10, grid = True, xlabel ='xlabel에 붙일 이름' )
plt.show()

#scatter로 시각화하기
plt.scatter(df["age"], df["fare"], c='red', alpha=0.2) # c=색상, alpha=투명도
plt.rcParams['figure.figsize'] = [15, 4]
plt.show()

# title 작성
plt.title('타이틀 이름')
plt.show()

#pie 그리기
plt.pie(df,labels= df_alone.columns , autopct='%.1f%%', startangle=260, counterclock=False)
plt.show()

#histo 그리기
df = pd.concat([df['age'],df['survived']], axis=1)
plt.xlabel('히스토그램')
plt.hist(df_age['age'], color="#7ef4fc",edgecolor="#d1fcff",)
plt.show()
# Seaborn

# violinplot 그리기
p = sns.violinplot(data=df, x='species',y='flipper_length_mm',hue='sex' )
			# x축은 species, y축은 날개길이, hue는 성별 (한 종에 나눠서 넣을 구분)
			# Output, x축에 각 종이그려지고, 종별로 성별로 나뉘어 그려진다. 
# 타이틀과 레전드 넣기
plt.title('종별 성별별 날개의 길이 분포\n', fontsize=20)
plt.legend(loc='upper right')

# 주석 넣기
ax = plt.gca()
ax.text(.6, .65, "Annotation달기(차태 내에 주석넣기)", transform=ax.transAxes)
plt.show()

#FacetGrid (나눠그리기)
facetgrid_df = sns.FacetGrid(df, row="sex", col="island", hue="species")
		#row별로 sex(위 male, 아래 female)
        #columns별로는 island (첫번째섬, 둘째섬, 셋째섬) 
facetgrid_df.map(sns.kdeplot, "body_mass_g", "flipper_length_mm")
		#각 그릴 그림은 (bodymass와 flipper의 밀도)
plt.show()

#추세선 넣어서 그리기
df1 = pd.concat([df['species'],df['body_mass_g'],df['bill_length_mm']],axis =1 )
sns.lmplot(data=df1, x='body_mass_g', y='bill_length_mm')

#outlier 발견시 (예: 이상값 1000이상, 다른 건 400이하) 
newDF = df[df['feature'] < 1000]

 

반응형

댓글