You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
in_file='./data/data.csv'out_file='./data/tem10y.csv'# csv 파일을 한 줄 씩 읽어 들이기withopen(in_file, 'rt', encoding='EUC_KR') asfr: # excel 등에서 출력한 csv 파일을 포함해 한국어가 들어가 있는 csv 파일은 EUC_KR인 경우가 많음lines=fr.readlines()
# 기존의 데이터를 분리해서 가공하기lines= ['연,월,일,기온,품질,균질\n'] +lines[5:]
lines=map(lambdav: v.replace('/',','),lines)
result=''.join(lines).strip()
# 결과를 파일에 출력withopen(out_file, 'wt', encoding='utf-8') asfw:
fw.write(result)
print('saved')
importpandasaspd# pandas로 csv 파일 읽어 들이기df=pd.read_csv('./data/tem10y.csv', encoding='utf-8')
# 날짜별 기온을 리스트에 넣기md= {}
fori, rowindf.iterrows(): # DataFrame 자료형의 데이터를 한 줄씩 처리하고 싶을 때는 for 반복문과 df.iterrows() 조합해서 사용m, d, v= (int(row['월']), int(row['일']), float(row['기온']))
key=str(m) +'/'+str(d)
ifnot(keyinmd): md[key] = []
md[key] += [v]
# 날짜별 평균 구하기avs= {}
forkeyinmd:
v=avs[key] =sum(md[key]) /len(md[key])
print('{0} : {1}'.format(key, v))
책의 월별 평균
importmatplotlib.pyplotaspltimportpandasaspd#csv 파일 읽어 들이기df=pd.read_csv('./data/tem10y.csv', encoding='utf-8')
# 월별 평균 구하기g=df.groupby(['월'])['기온']
gg=g.sum() /g.count()
# 결과 출력하기print(gg)
gg.plot()
plt.show()
기온이 30도 넘는 날 구하기
importmatplotlib.pyplotaspltimportpandasaspd# 파일 읽기df=pd.read_csv('./data/tem10y.csv', encoding='utf-8')
# 온도가 30도를 넘는 데이터 확인hot_bool= (df['기온'] >30) # 이전에 써왔던 condition 변수와 같음# 데이터 추출hot=df[hot_bool]
# 연별로 세기cnt=hot.groupby(['연'])['연'].count() # 연으로 그룹화하고 연 칼럼만 사용하겠다# 출력하기print(cnt)
cnt.plot()
plt.show()
회귀 분석으로 내일 기온 예측
fromsklearn.linear_modelimportLinearRegressionimportpandasaspdimportnumpyasnpimportmatplotlib.pyplotasplt# 기온 데이터 읽기df=pd.read_csv('./data/tem10y.csv', encoding='utf-8')
# 데이터를 학습 전용과 테스트 전용으로 분리# 데이터에는 2016년까지 있음train_year= (df['연'] <=2015)
test_year= (df['연'] >=2015)
interval=6# 과거 6일의 데이터를 기반으로 학습할 데이터 만들기defmake_data(data):
x= [] # 학습 데이터, 설명 변수y= [] # 결과, 목적 변수temps=list(data['기온'])
foriinrange(len(temps)):
ifi<interval: continuey.append(temps[i])
xa= []
forpinrange(interval):
d=i+p-intervalxa.append(temps[d])
x.append(xa)
return (x, y)
train_x, train_y=make_data(df[train_year])
test_x, test_y=make_data(df[test_year])
# 직선 회귀 분석하기lr=LinearRegression(normalize=True)
lr.fit(train_x, train_y) # 학습하기pre_y=lr.predict(test_x) # 예측하기# 결과를 그래프로 그리기plt.figure(figsize= (10,6), dpi=100)
plt.plot(test_y, c='r') # 실제 기온plt.plot(pre_y, c='b') # 예측 기온plt.show()