K-디지털트레이닝(빅데이터) 21일차

유현민·2021년 9월 1일
0

오늘은 판다스로 그래프 그리기, 데이터프레임 조작, 누락값 처리에 관해 배웠다.

앤스콤 데이터 집합 불러온 후 그래프 그리기

1. 앤스콤 데이터 집합 불러오기

import seaborn as sns                       # 앤스콤 데이터 집합은 seaborn 라이브러리에 포함됨 
anscombe = sns.load_dataset("anscombe")  
print(anscombe)
print(type(anscombe))

anscombe.groupby('dataset')[['x','y']].mean()   # dataset x,y 평균으로 groupby 함 

anscombe.groupby('dataset')[['x','y']].var()  # dataset x,y 분산(variance)으로 groupby 함 

anscombe.groupby('dataset')[['x','y']].std() # dataset x,y 표준편차으로 groupby 함 

%matplotlib inline
import matplotlib.pyplot as plt         # matplotlib 라이브러리 불러오기 

dataset_1 = anscombe[anscombe['dataset'] == 'I']  #dataset1 에 anscombe 데이터프레임 데이터 I 값 저장하기 
 
dataset_1

plt.plot(dataset_1['x'], dataset_1['y'])   # plot 매서드로 그리기 

plt.plot(dataset_1['x'], dataset_1['y'], 'o')   #점으로 표현해보기 

dataset_2 = anscombe[anscombe['dataset'] == 'II']   # dataset2 에 anscombe 데이터프레임 데이터 II 값 저장하기 
dataset_3 = anscombe[anscombe['dataset'] == 'III']  
dataset_4 = anscombe[anscombe['dataset'] == 'IV']

fig = plt.figure()  # fig 는 기본틀 

axes1 = fig.add_subplot(2, 2, 1)   # fig에 격자를 추가한다는 기분으로 add_subplot 메서드 사용
axes2 = fig.add_subplot(2, 2, 2)   # 기본틀 행렬 값 2x2, 2사분변 의미  
axes3 = fig.add_subplot(2, 2, 3)   #axes는 개별그래프를 나타내는 ax어레이 객체임 
axes4 = fig.add_subplot(2, 2, 4)

axes1.plot(dataset_1['x'], dataset_1['y'], 'o')   # plot 메서드에 데이터 전달하여 그래프 그리기, 점으로 표현 
axes2.plot(dataset_2['x'], dataset_2['y'], 'o') 
axes3.plot(dataset_3['x'], dataset_3['y'], 'o') 
axes4.plot(dataset_4['x'], dataset_4['y'], 'o')

fig   # fig를 입력하여야 그래프 확인 가능 

axes1.set_title("dataset_1")   # 각 그래프 격자(axes)에 제목 추가하기 
axes2.set_title("dataset_2")
axes3.set_title("dataset_3") 
axes4.set_title("dataset_4")

fig

fig.suptitle("Anscombe Data")    # 기본 틀(fig)에 제목 추가하기 

fig

fig.tight_layout()     # tight_layout  메서드를 호출하여 이름과 숫자 겹치는거 레이아웃 조절하기 

fig

기초 그래프 그리기 ― 히스토그램, 산점도, 박스 그래프

tips = sns.load_dataset("tips")     # seaborn 라이브러리에서 tip 데이터 불러와서 변수 tips로 저장하기 
print(tips.head())
print(type(tips))

fig = plt.figure()    # 기본틀 그려주고 
axes1 = fig.add_subplot(1, 1, 1)  # 격자 행렬 값 1x1, 1사분변 의미

axes1.hist(tips['total_bill'], bins=5)        # hist 메서드에 total bill 열을 전달하여 히스토그램 만들기 bin은 x축 간격
axes1.set_title('Histogram of Total Bill')     
axes1.set_xlabel('Frequency')                  # title, label 이름 넣어주기 
axes1.set_ylabel('Total Bill') 

fig    # 결과값 출력시 fig 입력 

scatter_plot = plt.figure()                        # 기본틀 그려주고     
axes1 = scatter_plot.add_subplot(1, 1, 1)           # 격자 행렬 값 1x1, 1사분변 의미  
axes1.scatter(tips['total_bill'], tips['tip'])       # scatter 메서드에 total bill, tip 열 전달  
axes1.set_title('Scatterplot of Total Bill vs Tip') 
axes1.set_xlabel('Total Bill') 
axes1.set_ylabel('Tip')

boxplot = plt.figure()                            # boxplot 기본틀 만들기 
axes1 = boxplot.add_subplot(1, 1, 1)               # 격자 모양 1x1 행렬, 1사분면 

axes1.boxplot( 
    [tips[tips['sex'] == 'Female']['tip'],        # 여성의 팁, 남성의 팁 넣어주고 
     tips[tips['sex'] == 'Male']['tip']], 
    labels=['Female', 'Male'])


axes1.set_xlabel('Sex') 
axes1.set_ylabel('Tip') 
axes1.set_title('Boxplot of Tips by Sex')

다변량 데이터로 다변량 그래프 그리기 ─ 산점도 그래프

def recode_sex(sex):             # 지불금액, 팁, 성별 사용하여 다변량 그래프 그리기              
    if sex == 'Female':
        return 0 
    else:
        return 1

tips['sex_color'] = tips['sex'].apply(recode_sex)  # recode_sex 값으로 sex_color 값 구분 

scatter_plot = plt.figure()   # scatter plot 기본틀 잡아주고
axes1 = scatter_plot.add_subplot(1, 1, 1)  # 격자모양 
axes1.scatter(
    x=tips['total_bill'],           
    y=tips['tip'],    
    s=tips['size'] * 10,     # s는 테이블당 인원수 
    c=tips['sex_color'],
    alpha=0.5)   # 0.5는 점의 투명도 

axes1.set_title('Total Bill vs Tip Colored by Sex and Sized by Size') 
axes1.set_xlabel('Total Bill') 
axes1.set_ylabel('Tip') 

단변량 그래프 그리기 ― 히스토그램

import seaborn as sns

tips = sns.load_dataset("tips")

ax = plt.subplots()     # subplots를 이용하여 히스토그램 기본틀 만들어 주기 
ax = sns.distplot(tips['total_bill'])  # tips 데이터에서 total bill열데이터 전달 , displot 메서드 사용시 히스토그램, 밀집도 그래프 
ax.set_title('Total Bill Histogram with Density Plot')

ax = plt.subplots() 
ax = sns.distplot(tips['total_bill'], kde=False)   # 밀집도 그래프 제외하기 
ax.set_title('Total Bill Histogram') 
ax.set_xlabel('Total Bill') 
ax.set_ylabel('Frequency')

ax = plt.subplots() 
ax = sns.distplot(tips['total_bill'], hist=False) # 히스토그램 제외하기 
ax.set_title('Total Bill Density') 
ax.set_xlabel('Total Bill') 
ax.set_ylabel('Unit Probability')

ax = plt.subplots() 
ax = sns.distplot(tips['total_bill'], rug=True) # rug 인자 추가하기 
ax.set_title('Total Bill Histogram with Density and Rug Plot') 
ax.set_xlabel('Total Bill')

ax = plt.subplots() # 기본틀 만들어 주기 
ax = sns.countplot('day', data=tips) # count 그래프(이산값을 나타냄) 그리기 
ax.set_title('Count of days') 
ax.set_xlabel('Day of the Week') 
ax.set_ylabel('Frequency') 

다양한 종류의 이변량 그래프 그리기

1. seaborn 라이브러리로 산점도 그래프 그리기

ax = plt.subplots() 
ax = sns.regplot(x='total_bill', y='tip', data=tips) # regplot 산점도+ 회귀선 
ax.set_title('Scatterplot of Total Bill and Tip') 
ax.set_xlabel('Total Bill') 
ax.set_ylabel('Tip') 

ax = plt.subplots() 
ax = sns.regplot(x='total_bill', y='tip', data=tips, fit_reg=False) # 회귀선 제외하기 
ax.set_title('Scatterplot of Total Bill and Tip') 
ax.set_xlabel('Total Bill') 
ax.set_ylabel('Tip') 

joint = sns.jointplot(x='total_bill', y='tip', data=tips)     #jointplot 메서드 사용 , 데이터 가져오기 
joint.set_axis_labels(xlabel='Total Bill', ylabel='Tip')
joint.fig.suptitle('Joint Plot of Total Bill and Tip', fontsize=20, y=1.03)

hexbin = sns.jointplot(x="total_bill", y="tip", data=tips, kind="hex") #육각그래프 그리기 , 데이터 가져오기 
hexbin.set_axis_labels(xlabel='Total Bill', ylabel='Tip')
hexbin.fig.suptitle('Hexbin Joint Plot of Total Bill and Tip', fontsize=10, y=1.03)

4. 이차원 밀집도 그리기

ax = plt.subplots() 
ax = sns.kdeplot(data=tips['total_bill'],  #kdeplot 메서드 만들기 
                 data2=tips['tip'], 
                 shade=True)    # 음영효과 주기 
ax.set_title('Kernel Density Plot of Total Bill and Tip') 
ax.set_xlabel('Total Bill') 
ax.set_ylabel('Tip') 

5. 바 그래프 그리기

ax = plt.subplots() #틀 그리기 
ax = sns.barplot(x='time', y='total_bill', data=tips) 
ax.set_title('Bar plot of average total bill for time of day') 
ax.set_xlabel('Time of day') 
ax.set_ylabel('Average total bill')

tips

6. 박스 그래프 그리기

ax = plt.subplots() 
ax = sns.boxplot(x='time', y='total_bill', data=tips) 
ax.set_title('Boxplot of total bill by time of day') 
ax.set_xlabel('Time of day') 
ax.set_ylabel('Total Bill') 

ax = plt.subplots() 
ax = sns.violinplot(x='time', y='total_bill', data=tips) 
ax.set_title('Violin plot of total bill by time of day') 
ax.set_xlabel('Time of day') 
ax.set_ylabel('Total Bill')

8. 관계 그래프 그리기

fig = sns.pairplot(tips)

pair_grid = sns.PairGrid(tips) 
pair_grid = pair_grid.map_upper(sns.regplot) # regplot 은 산점도 +회귀선
pair_grid = pair_grid.map_lower(sns.kdeplot)  # 이차원 밀집도 
pair_grid = pair_grid.map_diag(sns.distplot, rug=True) 
plt.show()

다변량 그래프 그리기

1. seaborn 라이브러리로 바이올린 그래프 그리기 ― 색상 추가

ax = plt.subplots() 
ax = sns.violinplot(x='time', y='total_bill', hue='sex', data=tips, split=True) 
plt.show()

2. 산점도, 관계 그래프 그리기 ― 색상 추가

scatter = sns.lmplot(x='total_bill', y='tip', data=tips, hue='sex', fit_reg=False)  # fit_reg=False 회귀선 삭제 
plt.show()

fig = sns.pairplot(tips, hue='sex')

3. 산점도 그래프의 크기와 모양 조절하기

scatter = sns.lmplot(x='total_bill', y='tip', data=tips, fit_reg=False, hue='sex', scatter_kws={'s': tips['size']*10}) 
plt.show()

scatter = sns.lmplot(x='total_bill', y='tip', data=tips, fit_reg=False, hue='sex', scatter_kws={'s':50}) 

plt.show()

scatter = sns.relplot(x='total_bill', y='tip', data=tips, hue='sex', size=tips['size']*30)

scatter = sns.lmplot(x='total_bill', y='tip', data=tips, fit_reg=False, hue='sex', markers=['o', 'x'], scatter_kws={'s': tips['size']*10}) 
plt.show()

scatter = sns.lmplot(x='total_bill', y='tip', data=tips, fit_reg=False, hue='sex', markers=['o', 'x'], scatter_kws={'s':50})  
plt.show()

5. lmplot 메서드로 4개의 데이터 그룹에 대한 그래프 한 번에 그리기

anscombe_plot = sns.lmplot(x='x', y='y', data=anscombe, fit_reg=False) # fit_reg=False 회귀선 없애기 

anscombe_plot = sns.lmplot(x='x', y='y', data=anscombe, fit_reg=False, col='dataset', col_wrap=1) #col_wrap=3 3개씩 보기 

FacetGrid 클래스로도 그룹별 그래프를 그릴 수 있습니다

facet = sns.FacetGrid(tips, col='time') # time 으로 나눔 
facet.map(sns.distplot, 'total_bill', rug=True) 

facet = sns.FacetGrid(tips, col='day', hue='sex')  # day로 나누고 성별구분 
facet = facet.map(plt.scatter, 'total_bill', 'tip') 
facet = facet.add_legend() 

facet = sns.FacetGrid(tips, col='day', hue='sex')  # day로 나누고 성별구분 
facet = facet.map(plt.scatter, 'total_bill', 'tip') 


facet = sns.FacetGrid(tips, col='time', row='smoker', hue='sex') 
facet.map(plt.scatter, 'total_bill', 'tip') 

데이터프레임과 시리즈로 그래프 그리기

fig, ax = plt.subplots()
ax = tips['total_bill'].plot.hist() 

fig, ax = plt.subplots() 
ax = tips[['total_bill', 'tip']].plot.hist(alpha=1, bins=10, ax=ax) 

fig, ax = plt.subplots() 
ax = tips['tip'].plot.kde() 

fig, ax = plt.subplots() 
ax = tips.plot.scatter(x='total_bill', y='tip', ax=ax) 

fig, ax = plt.subplots() 
ax = tips.plot.hexbin(x='total_bill', y='tip', ax=ax) 

fig, ax = plt.subplots() 
ax = tips.plot.hexbin(x='total_bill', y='tip', gridsize=10, ax=ax) 

fig, ax = plt.subplots() 
ax = tips.plot.box(ax=ax) 

그래프에 스타일 적용하기

fig, ax = plt.subplots() 
ax = sns.violinplot(x='time', y='total_bill', hue='sex', data=tips, split=True) 

sns.set_style('whitegrid') # 스타일 설정 
fig, ax = plt.subplots() 
ax = sns.violinplot(x='time', y='total_bill', hue='sex', data=tips, split=True) 

fig = plt.figure() 
seaborn_styles = ['darkgrid', 'whitegrid', 'dark', 'white', 'ticks'] # 스타일 설정하여 그려보기 
for idx, style in enumerate(seaborn_styles):
    plot_position = idx + 1
    with sns.axes_style(style):
        ax = fig.add_subplot(2, 3, plot_position)  # 2x3 행렬
        violin = sns.violinplot(x='time', y='total_bill', data=tips, ax=ax)
        violin.set_title(style) 
        
fig.tight_layout() 

데이터 연결하기

1. concat 메서드로 데이터 연결하기

import pandas as pd

df1 = pd.read_csv('data2/concat_1.csv') 
df2 = pd.read_csv('data2/concat_2.csv') 
df3 = pd.read_csv('data2/concat_3.csv')

df1

df2

df3

row_concat = pd.concat([df1, df2, df3]) # concat으로 데이터 연결하기 
print(row_concat)

print(row_concat.iloc[3, ]) 

### 4. 데이터프레임에 시리즈 연결하기

new_row_series = pd.Series(['n1', 'n2', 'n3', 'n4'])

new_row_series

df1

print(pd.concat([df1, new_row_series])) # 시리즈에 열이름이 없어서 아래 새로운 행에 열 0을 만들어 붙임 

행 1개로 구성된 데이터프레임 생성하여 연결하기

new_row_df = pd.DataFrame([['n1', 'n2', 'n3', 'n4']], columns=['A', 'B', 'C', 'D']) # 컬럼 이름이 있어 컬럼 밑에 붙음 
print(new_row_df)

print(pd.concat([df1, new_row_df])) # A,B,C,D  열 이름이 있어 아래에 붙음 

print(df1.append(new_row_df)) # concat 대신 append 사용가능 연결할 데이터 프레임이 1개라면 

data_dict = {'A': 'n1', 'B': 'n2', 'C': 'n3', 'D': 'n4'}
print(df1.append(data_dict, ignore_index=True))              # ignore_index=True) = 인덱스를 0부터 다시 지정하기 

다양한 방법으로 데이터 연결하기

1. ignore_index 인자 사용하기

row_concat_i = pd.concat([df1, df2, df3], ignore_index=True) 
print(row_concat_i)

2. 열 방향으로 데이터 연결하기

col_concat = pd.concat([df1, df2, df3], axis=1)  # axis=1 열 방향으로 데이터 연결하기 
col_concat

print(col_concat['A'])

col_concat['new_col_list'] = ['n1', 'n2', 'n3', 'n4']  # 새로운 열 추가하기 
print(col_concat)

print(pd.concat([df1, df2, df3], axis=1, ignore_index=True))  # 열로 데이터 붙이고, 인덱스 번호 새로 정의 

6. 공통 열과 공통 인덱스만 연결하기

df1.columns = ['A', 'B', 'C', 'D'] 
df2.columns = ['E', 'F', 'G', 'H'] 
df3.columns = ['A', 'C', 'F', 'H']
df1


df2


df3


row_concat = pd.concat([df1, df2, df3]) 
print(row_concat)

print(pd.concat([df1, df2, df3], join='inner')) # join='inner 3개가 모두 있는 공통된 열 없음 

print(pd.concat([df1,df3], ignore_index=False, join='inner')) #ignore_index=False 인덱스 0부터 새로 정열 하지 않음

df1.index = [0, 1, 2, 3]   # 인덱스 정의 해주기 
df2.index = [4, 5, 6, 7] 
df3.index = [0, 2, 5, 7]

print(df1)

print(df2)

print(df3)

col_concat = pd.concat([df1, df2, df3], axis=1)  # concat 메서드는 행으로 붙이기지만, 열로 지정하여 붙이기 
print(col_concat)

print(pd.concat([df1, df3], axis=1, join='inner'))

merge 메서드 사용하기

person = pd.read_csv('data2/survey_person.csv') 
site = pd.read_csv('data2/survey_site.csv') 
survey = pd.read_csv('data2/survey_survey.csv') 
visited = pd.read_csv('data2/survey_visited.csv')

print(person)

print(site)

print(visited)   # 날씨 관측 날짜 

print(survey)  

visited_subset = visited.loc[[0, 2, 6], ]
print(visited_subset)   # 인덱스로 슬라이싱

print(site)

print(visited_subset)  

o2o_merge = site.merge(visited_subset, left_on='name', right_on='site')  # merge 메서드 사용 
print(o2o_merge)

print(site)

print(visited)

m2o_merge = site.merge(visited, left_on='name', right_on='site') 
print(m2o_merge)

person

survey

ps = person.merge(survey, left_on='ident', right_on='person')  # person, survey merge
vs = visited.merge(survey, left_on='ident', right_on='taken')  # visited , survey merge 

print(ps) # ident= person 

print(vs) # ident = taken  

ps_vs = ps.merge(vs, left_on=['ident','taken', 'quant'], right_on=['person','ident', 'quant'])

ps_vs

ps_vs = ps.merge(vs, left_on=['ident','reading'], right_on=['person','reading'])

ps_vs 

print(ps_vs.loc[0, ])

누락값 확인하기

from numpy import NaN, NAN, nan

print(NaN == True)

print(NaN == False)

print(NaN == 0)

print(NaN == '')

---

print(NaN == NaN)

print(NaN == nan)

print(NaN == NAN)

print(nan == NAN)

---

import pandas as pd 

print(pd.isnull(NaN))

print(pd.isnull(nan))

print(pd.isnull(NAN))

print(pd.notnull(NaN))

print(pd.notnull(42))

print(pd.notnull('missing'))

누락값이 생기는 이유 알아보기

1. 누락값이 있는 데이터 집합을 연결할 때 누락값이 생기는 경우

visited = pd.read_csv('data2/survey_visited.csv') 
survey = pd.read_csv('data2/survey_survey.csv')

print(visited)

print(survey)

vs = visited.merge(survey, left_on='ident', right_on='taken') 
print(vs)

3. 데이터를 입력할 때 누락값이 생기는 경우

num_legs = pd.Series({'goat': 4, 'amoeba': nan}) 
print(num_legs)
print(type(num_legs))

scientists = pd.DataFrame({ 
    'Name': ['Rosaline Franklin', 'William Gosset'], 
    'Occupation': ['Chemist', 'Statistician'], 
    'Born': ['1920-07-25', '1876-06-13'], 
    'Died': ['1958-04-16', '1937-10-16'], 
    'missing': [NaN, nan]}) 

print(scientists)
print(type(scientists))

4. 범위를 지정하여 데이터를 추출할 때 누락값이 생기는 경우

gapminder = pd.read_csv('data2/gapminder.tsv', sep='\t')

life_exp = gapminder.groupby(['year'])['lifeExp'].mean() 
print(life_exp)

print(life_exp.loc[range(2000, 2010), ])

y2000 = life_exp[life_exp.index > 2000] 
print(y2000)

누락값의 개수 구하기

ebola = pd.read_csv('data2/country_timeseries.csv')

print(ebola.count())

num_rows = ebola.shape[0]
num_missing = num_rows - ebola.count() 
print(num_missing)

import numpy as np 

print(np.count_nonzero(ebola.isnull()))

print(np.count_nonzero(ebola['Cases_Guinea'].isnull()))

ebola

print(ebola.Cases_Guinea.value_counts(dropna=False).head())

누락값 처리하기 ― 변경, 삭제

1. 누락값 변경하기

print(ebola.fillna(0).iloc[0:10, 0:5])

print(ebola.fillna(method='ffill').iloc[0:10, 0:5])

print(ebola.fillna(method='bfill').iloc[0:10, 0:5])

print(ebola.interpolate().iloc[0:10, 0:5])

5. 누락값 삭제하기

print(ebola.shape)

ebola_dropna = ebola.dropna() 
print(ebola_dropna.shape)

print(ebola_dropna)

누락값이 포함된 데이터 계산하기

ebola['Cases_multiple'] = ebola['Cases_Guinea'] + ebola['Cases_Liberia'] + ebola['Cases_SierraLeone']

ebola_subset = ebola.loc[:, ['Cases_Guinea', 'Cases_Liberia', 'Cases_SierraLeone', 'Cases_multiple']] 
print(ebola_subset.head(n=10))

print(ebola.Cases_Guinea.sum(skipna = True))

print(ebola.Cases_Guinea.sum(skipna = False))
profile
smilegate megaport infra

0개의 댓글