오늘은 apply메서드, groupby, 집계 메서드, 누락값 처리방법, 그룹 오브젝트, datetime, 테슬라 주식 데이터로 분석하기 를 배웠다.
def my_sq(x):
return x ** 2 # 제곱 함수 만들기
def my_exp(x, n):
return x ** n # n제곱 함수 만들기
print(my_sq(4)) # 4의 제곱
print(my_exp(2, 4)) # 2의 4제곱
import pandas as pd
df = pd.DataFrame({'a': [10, 20, 30], 'b': [20, 30, 40]})
print(df) # 데이터 프레임 준비
print(df['a'] ** 2) # a열 제곱하여 제곱값 구하기
sq = df['a'].apply(my_sq) # apply 메서드에 제곱 함수 (my_sq)를 전달하여 시리즈의 모든 데이터 제곱 함수 적용
print(sq)
ex = df['a'].apply(my_exp, n=2) # apply 메서드와 my_exp 함께 사용 ,제곱
print(ex)
ex = df['a'].apply(my_exp, n=3) # 세제곱
print(ex)
df = pd.DataFrame({'a': [10, 20, 30], 'b': [20, 30, 40]}) #데이터 프레임 만들기
print(df)
def print_me(x): # 1개의 값을 전달받아 출력하는 print_me 함수 만들기
print(x)
print(df.apply(print_me, axis=0)) #데이터 프레임에 함수적용 , axis = 0 이면 열방향, axis = 1이면 행방향
print(df['a'])
print(df['b'])
def avg_3(x, y, z):
return (x + y + z) / 3 # 3개의 인자를 받아 평균을 구하는 함수 만들기
print(df.apply(avg_3)) # 3개의 인자값이 필요한 함수인데 1개의 인자값만 입력받아서 오류 메세지 출력
# df['a'] 또는 df['b'] 가 전달되었고 이값을 1개의 인자로 인식함 따라서 열단위 데이터로
# 처리 할 수 있게 수정하기
df
def avg_3_apply(col): # df['a'] 값 각각의 column 값을 넣어줌
x = col[0]
y = col[1]
z = col[2]
return (x + y + z) / 3
print(df.apply(avg_3_apply))
print(df['a'])
print(df['b'])
df
def avg_3_apply(col): # 열 방향으로 모든 파라메트 값의 평균 구하기
sum = 0
for item in col:
sum += item
return sum / df.shape[0]
print(df.apply(avg_3_apply, axis = 0))
def avg_2_apply(row):
sum = 0
for item in row: # 행 방향으로 모든 파라메트 값의 평균 구하기 a와 b 행으로 더하고 평균구하기
sum += item
return sum / df.shape[1]
print(df.apply(avg_2_apply, axis = 1))
import seaborn as sns
titanic = sns.load_dataset("titanic") # 타이타닉 데이터 불러오기
print(titanic.info())
import numpy as np
def count_missing(vec): # 누락값 개수 반황 count_missing
null_vec = pd.isnull(vec) # pd.isnull 메서드는 누락값 유,무에 따라 true/ false 적용
null_count = np.sum(null_vec) # true / false값을 sum 하여 count함
return null_count
cmis_col = titanic.apply(count_missing) # apply 메서드에 count_missing 함수 전달
print(cmis_col)
def prop_missing(vec): #prop_missing 누락값의 비율을 계산함
num = count_missing(vec) # 누락값 개수 반환 하는 count_missing 함수 이용 하여 누락값구하기
dem = vec.size #size 속성을 이용해 데이터프레임의 전체 데이터 수 구하기
return num / dem # 누락값/ 전체 데이터수
pmis_col = titanic.apply(prop_missing) #누락값 비율 구하기
print(pmis_col)
def prop_complete(vec): # 전체비율 (1)에서 누락값의 비율 빼기
return 1 - prop_missing(vec)
prop_complete
cmis_row = titanic.apply(count_missing, axis=1) #행의 누락값
pmis_row = titanic.apply(prop_missing, axis=1) #누락값의 비율
pcom_row = titanic.apply(prop_complete, axis=1) # 누락값이 아닌 값의 비율
print(cmis_row.head(15)) # 행의 누락값
print(pmis_row.head()) # 누락값의 비율
print(pcom_row.head()) #누락값이 아닌 값의 비율
titanic['num_missing'] = titanic.apply(count_missing, axis=1) # 누락값의 개수를 구하여 타이타닉 데이터 프레임에 추가하기
print(titanic)
print(titanic.loc[titanic.num_missing > 1, :].sample(10)) # 누락값이 2개 이상인 데이터 추출하기
import pandas as pd
df = pd.read_csv('data2/gapminder.tsv', sep='\t') # 갭마인더 데이터 불러오기
avg_life_exp_by_year = df.groupby('year').lifeExp.mean() # year을 기준으로 기대수명 평균 구하기
print(avg_life_exp_by_year)
# avg_life_exp_by_year = df.groupby('year')['lifeExp'].mean()
# print(avg_life_exp_by_year)
years = df.year.unique() # 중복없이 year 데이터 뽑기 (분할작업)
print(years)
y1952 = df.loc[df.year == 1952, :] # 1952년 데이터 추출 하기 (반영작업)
print(y1952.head())
y1952_mean = y1952.lifeExp.mean() #1952년 기대수명 평균구하기 (반영작업)
print(y1952_mean)
y1957 = df.loc[df.year == 1957, :]
y1957_mean = y1957.lifeExp.mean( )
print(y1957_mean)
y1962 = df.loc[df.year == 1962, :]
y1962_mean = y1962.lifeExp.mean( )
print(y1962_mean)
y2007 = df.loc[df.year == 2007, :]
y2007_mean = y2007.lifeExp.mean( )
print(y2007_mean)
df2 = pd.DataFrame({"year":[1952, 1957, 1962, 2007], # 연도별 계산한 평균값 합치기 (결합작업)
"mean ":[y1952_mean, y1957_mean,y1962_mean,y2007_mean]})
print(df2)
def my_mean(values):
n = len(values) # 입력받은 열의 평균값을 구하는 함수
sum = 0
for value in values:
sum += value
return sum / n
agg_my_mean = df.groupby('year').lifeExp.agg(my_mean) #위에서 만든 함수와 groupby 메서드 조합하기 위해 agg메서드 사용
print(agg_my_mean)
def my_mean_diff(values, diff_value): # 첫번째 인자로 받은 열의 평균값을 구하여 두번째 인자로 받은
n = len(values) # 값과의 차이를 계신
sum = 0
for value in values:
sum += value
mean = sum / n
return mean - diff_value
global_mean = df.lifeExp.mean()
print(global_mean) # 전체 평균 수명 구하기
agg_mean_diff = df.groupby('year').lifeExp.agg(my_mean_diff, diff_value=global_mean)
print(agg_mean_diff) # 연도별 평균 수명 - 전체 평균 수명
import numpy as np
gdf = df.groupby('year').lifeExp.agg([np.count_nonzero, np.mean, np.std])
print(gdf) # 0이 아닌개수, 평균, 표준편차
gdf_dict = df.groupby('year').agg({'lifeExp': 'mean', 'pop': 'median', 'gdpPercap': 'median'})
print(gdf_dict) # 집계 메서드를 딕션너리에 담아 agg 메서드 전달
def my_zscore(x):
return (x - x.mean()) / x.std() # z-score 평균 0, 표준편차 1
transform_z = df.groupby('year').lifeExp.transform(my_zscore) #transform 메서드를 사용하여 각 연도별
# 기대수명 표준점수 계산
print(transform_z.head())
print(df.shape)
print(transform_z.shape)
import seaborn as sns
import numpy as np
np.random.seed(42) # random 함수 넣어주고
tips_10 = sns.load_dataset('tips').sample(10) # sample 10개 뽑기
tips_10.loc[np.random.permutation(tips_10.index)[:4], 'total_bill'] = np.NaN
# 열의 값 4개를 임의로 선택하여 누락값으로 바꾸기
print(tips_10)
count_sex = tips_10.groupby('sex').count()
print(count_sex)
def fill_na_mean(x):
avg = x.mean()
return x.fillna(avg) # 누락값을 평균값으로 처리하기
total_bill_group_mean = tips_10.groupby('sex').total_bill.transform(fill_na_mean)
tips_10['fill_total_bill'] = total_bill_group_mean
print(tips_10)
tips = sns.load_dataset('tips')
print(tips.shape)
tips
tips['size'].value_counts()
tips_filtered = tips.\
groupby('size').\
filter(lambda x: x['size'].count() >= 30)
# 30이상인 사이즈만 출력하기
print(tips_filtered.shape)
print(tips_filtered['size'].value_counts())
tips_10 = sns.load_dataset('tips').sample(10, random_state=42)
print(tips_10)
grouped = tips_10.groupby('sex')
print(grouped)
print(grouped.groups)
avgs = grouped.mean()
print(avgs)
print(tips_10.columns)
그룹 오브젝트 활용 참고
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html
female = grouped.get_group('Female')
print(female)
for sex_group in grouped:
print(sex_group)
for sex_group in grouped:
print('the type is: {}\n'.format(type(sex_group)))
print('the length is: {}\n'.format(len(sex_group)))
first_element = sex_group[0]
print('the first element is: {}\n'.format(first_element))
print('it has a type of: {}\n'.format(type(sex_group[0])))
second_element = sex_group[1]
print('the second element is:\n{}\n'.format(second_element))
print('it has a type of: {}\n'.format(type(second_element)))
print('what we have:')
print(sex_group)
break
bill_sex_time = tips_10.groupby(['sex', 'time'])
group_avg = bill_sex_time.mean()
print(group_avg)
print(type(group_avg))
print(group_avg.columns)
print(group_avg.index)
group_method = tips_10.groupby(['sex', 'time']).mean().reset_index()
print(group_method)
group_param = tips_10.groupby(['sex', 'time'], as_index=False).mean( )
print(group_param)
from datetime import datetime #datetime 날짜와 시간을 처리하는 파이썬 라이브러리
now1 = datetime.now()
print(now1)
now2 = datetime.today()
print(now2)
t1 = datetime.now()
t2 = datetime(1998, 12, 5)
t3 = datetime(1970, 12, 12, 13, 24, 34)
print(t1)
print(t2)
print(t3)
diff1 = t1 - t2
print(diff1)
print(type(diff1))
diff2 = t2 - t1
print(diff2)
print(type(diff2))
import pandas as pd
import os
ebola = pd.read_csv('data2/country_timeseries.csv')
print(ebola.info()) # date,day column
ebola['date_dt'] = pd.to_datetime(ebola['Date']) # to_datetime 매서드 사용하여 data 열의 자료형을
print(ebola.info()) # datetime 오브젝트로 변활할 수 있음
test_df1 = pd.DataFrame({'order_day':['01/01/15', '02/01/15', '03/01/15']})
test_df1['date_dt1'] = pd.to_datetime(test_df1['order_day'], format='%d/%m/%y')
test_df1['date_dt2'] = pd.to_datetime(test_df1['order_day'], format='%m/%d/%y')
test_df1['date_dt3'] = pd.to_datetime(test_df1['order_day'], format='%y/%m/%d')
print(test_df1)
test_df1 = pd.DataFrame({'order_day':['01/01/15', '02/01/15', '03/01/15']})
test_df1
test_df1['date_dt1'] = pd.to_datetime(test_df1['order_day'], format='%d/%m/%y')
test_df1
test_df1['date_dt2'] = pd.to_datetime(test_df1['order_day'], format='%m/%d/%y')
test_df1
test_df1['date_dt3'] = pd.to_datetime(test_df1['order_day'], format='%y/%m/%d')
test_df1
test_df2 = pd.DataFrame({'order_day':['01-01-15', '02-01-15', '03-01-15']})
test_df2['date_dt'] = pd.to_datetime(test_df2['order_day'], format='%d-%m-%y')
print(test_df2)
now = datetime.now()
print(now)
nowDate = now.strftime('%Y-%m-%d')
print(nowDate)
nowTime = now.strftime('%H:%M:%S')
print(nowTime)
nowDatetime = now.strftime('%Y-%m-%d %H:%M:%S')
print(nowDatetime)
ebola1 = pd.read_csv('data2/country_timeseries.csv', parse_dates=['Date'])
print(ebola1.info()) # parse_dates 에 datetime 오브젝트로 변환하고 싶은 column 넣기
date_series = pd.Series(['2018-05-16', '2018-05-17', '2018-05-18'])
d1 = pd.to_datetime(date_series) # date-series 생성하기
print(d1)
print(d1[0].year) # 오브젝트 d1의 0인덱스 year 값 출력
print(d1[0].month)
print(d1[0].day)
ebola = pd.read_csv('data2/country_timeseries.csv')
ebola['date_dt'] = pd.to_datetime(ebola['Date']) # 문자열 처리는 'string'
# datetime은 'dt' 접근자 사용
print(ebola[['Date', 'date_dt']].head())
print(ebola['date_dt'][3].year)
print(ebola['date_dt'][3].month)
print(ebola['date_dt'][3].day)
ebola['year'] = ebola['date_dt'].dt.year # year column 추가
print(ebola[['Date', 'date_dt', 'year']].head())
ebola['month'], ebola['day'] = (ebola['date_dt'].dt.month, ebola['date_dt'].dt.day)
print(ebola[['Date', 'date_dt', 'year', 'month', 'day']].head())
print(ebola.info())
print(ebola.iloc[-5:, :5])
print(ebola['date_dt'].min()) # 에볼라가 발생하기 시작한 날
print(type(ebola['date_dt'].min())) #timestamp는 datetime 오브젝트와 호환되는 자료형
ebola['outbreak_d'] = ebola['date_dt'] - ebola['date_dt'].min() # 에볼라의 최초 발병일을 빼기
print(ebola[['Date', 'Day', 'outbreak_d']].head())
banks = pd.read_csv('data2/banklist.csv')
print(banks.head())
banks_no_dates = pd.read_csv('data2/banklist.csv')
print(banks_no_dates.info())
banks = pd.read_csv('data2/banklist.csv', parse_dates=[5, 6]) #parse_dates 이용하여 datetime 오브젝트로 변황
print(banks.info())
banks
banks['closing_quarter'], banks['closing_year'] = (banks['Closing Date'].dt.quarter, banks['Closing Date'].dt.year)
print(banks.head()) #closing_quarter -은행의 파산분기, 년도 구하기
banks
closing_year = banks.groupby(['closing_year']).size()
print(closing_year)
closing_year_q = banks.groupby(['closing_year', 'closing_quarter']).size()
print(closing_year_q)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax = closing_year.plot()
plt.show()
fig, ax = plt.subplots()
ax = closing_year_q.plot()
plt.show()
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader as pdr
# tesla에는 데이터프레임이 저장됩니다.
tesla = pdr.get_data_quandl('TSLA', api_key = 'YcTTUyabiiSV_CrjeQcb')
# tesla에 저장된 데이터프레임을 파일로 저장합니다.
tesla.to_csv('data2/tesla_stock_quandl.csv')
print(tesla.head())
tesla = pd.read_csv('data2/tesla_stock_quandl.csv', parse_dates=[0])
print(tesla.info()) # date = parse_dates 사용하여 datetime으로 변경
tesla.loc[(tesla.Date.dt.year == 2018) & (tesla.Date.dt.month == 3)] # 2018.3월 데이터 출력
tesla.index = tesla['Date']
print(tesla.index)
tesla['Date'].min() # 최초의 데이터 수집일
tesla['ref_date'] = tesla['Date'] - tesla['Date'].min() # 데이터 간격 추출해보기
print(tesla.head())
tesla.index = tesla['ref_date']
print(tesla.iloc[:5, :5])
ebola = pd.read_csv('data2/country_timeseries.csv', parse_dates=[0])
print(ebola.iloc[:5, :5]) # 누락값이 보임
print(ebola.iloc[-5:, :5]) # 뒤쪽 데이터도 누락값이 보임
import matplotlib.pyplot as plt
ebola.index = ebola['Date']
fig, ax = plt.subplots()
ax = ebola.iloc[0:, 1:].plot(ax=ax)
ax.legend(fontsize=7, loc=2, borderaxespad=0.)
plt.show()
ebola
ebola_sub = ebola[['Day', 'Cases_Guinea', 'Cases_Liberia']]
print(ebola_sub.tail(10))
ebola = pd.read_csv('data2/country_timeseries.csv', parse_dates=['Date'])
print(ebola.head().iloc[:, :5])
ebola.index = ebola['Date']
new_idx = pd.date_range(ebola.index.min(), ebola.index.max())
print(new_idx)
new_idx = reversed(new_idx)
ebola = ebola.reindex(new_idx)
print(ebola.head().iloc[:, :5])
print(ebola.tail().iloc[:, :5])
last_valid = ebola.apply(pd.Series.last_valid_index)
print(last_valid)
first_valid = ebola.apply(pd.Series.first_valid_index)
print(first_valid)
earliest_date = ebola.index.min()
print(earliest_date)
shift_values = last_valid - earliest_date
print(shift_values)
ebola_dict = {}
for idx, col in enumerate(ebola):
d = shift_values[idx].days
shifted = ebola[col].shift(d)
ebola_dict[col] = shifted
ebola_shift = pd.DataFrame(ebola_dict)
print(ebola_shift.tail())
ebola_shift.index = ebola_shift['Day']
ebola_shift = ebola_shift.drop(['Date', 'Day'], axis=1)
print(ebola_shift.tail())
fig, ax = plt.subplots()
ax = ebola_shift.iloc[:, :].plot(ax=ax)
ax.legend(fontsize=7, loc=2, borderaxespad=0.9)
plt.show()