PYTHON LIBRARY/Project 연습 (새로운 개념 정리 추가!)

프로젝트(기온데이터분석) 연습 : 데이터 가공하여 히스토그램, 산점도 그리기 plt.hist() , plt.scatter()

신강희 2024. 4. 16. 23:44
728x90

 

# 실행에 필요한 기본 항목과 한글 인식하게하는 라이브러리 까지 한꺼번에 import

 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb

%matplotlib inline

import platform

from matplotlib import font_manager, rc
plt.rcParams['axes.unicode_minus'] = False

if platform.system() == 'Darwin':
    rc('font', family='AppleGothic')
elif platform.system() == 'Windows':
    path = "c:/Windows/Fonts/malgun.ttf"
    font_name = font_manager.FontProperties(fname=path).get_name()
    rc('font', family=font_name)
else:
    print('Unknown system... sorry~~~~')

 

< 기온데이터 분석 >

1907년부터 2018년3월까지의 서울 기온 데이터를 CSV로 다운로드 한다.

- 다운로드 파일을 미리 제공해서 폴더에 넣어두었습니다. seoul.csv 파일을 열어 보세요. encoding='cp949'

pd.read_csv('../data/seoul.csv')

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
Cell In[2], line 1
----> 1 pd.read_csv('../data/seoul.csv')

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\parsers\readers.py:948, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)
    935 kwds_defaults = _refine_defaults_read(
    936     dialect,
    937     delimiter,
   (...)
    944     dtype_backend=dtype_backend,
    945 )
    946 kwds.update(kwds_defaults)
--> 948 return _read(filepath_or_buffer, kwds)

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\parsers\readers.py:611, in _read(filepath_or_buffer, kwds)
    608 _validate_names(kwds.get("names", None))
    610 # Create the parser.
--> 611 parser = TextFileReader(filepath_or_buffer, **kwds)
    613 if chunksize or iterator:
    614     return parser

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\parsers\readers.py:1448, in TextFileReader.__init__(self, f, engine, **kwds)
   1445     self.options["has_index_names"] = kwds["has_index_names"]
   1447 self.handles: IOHandles | None = None
-> 1448 self._engine = self._make_engine(f, self.engine)

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\parsers\readers.py:1723, in TextFileReader._make_engine(self, f, engine)
   1720     raise ValueError(msg)
   1722 try:
-> 1723     return mapping[engine](f, **self.options)
   1724 except Exception:
   1725     if self.handles is not None:

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\io\parsers\c_parser_wrapper.py:93, in CParserWrapper.__init__(self, src, **kwds)
     90 if kwds["dtype_backend"] == "pyarrow":
     91     # Fail here loudly instead of in cython after reading
     92     import_optional_dependency("pyarrow")
---> 93 self._reader = parsers.TextReader(src, **kwds)
     95 self.unnamed_cols = self._reader.unnamed_cols
     97 # error: Cannot determine type of 'names'

File parsers.pyx:579, in pandas._libs.parsers.TextReader.__cinit__()

File parsers.pyx:668, in pandas._libs.parsers.TextReader._get_header()

File parsers.pyx:879, in pandas._libs.parsers.TextReader._tokenize_rows()

File parsers.pyx:890, in pandas._libs.parsers.TextReader._check_tokenize_status()

File parsers.pyx:2050, in pandas._libs.parsers.raise_parser_error()

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 0: invalid start byte

 

UnicodeDecodeError 가 뜨면 인코딩 에러로 UTF-8이 아닌것
# 이럴 경우 인코딩 확인하여 경로를 설정해주면 열림

df = pd.read_csv('../data/seoul.csv', encoding='cp949')

 

실습 1) 가장 더운날은 언제입니까?

# (1) .max() 사용

df['최고기온(℃)'].max()

38.4

 

df['최고기온(℃)'] == df['최고기온(℃)'].max()

0        False
1        False
2        False
3        False
4        False
         ...  
39921    False
39922    False
39923    False
39924    False
39925    False
Name: 최고기온(℃), Length: 39926, dtype: bool

 

df.loc[ df['최고기온(℃)'] == df['최고기온(℃)'].max() ,  ]

 

# (2) sort_values()를 사용하여 바로 확인

df.sort_values('최고기온(℃)')

 

실습 2) 최고기온을 히스토그램으로 나타내되, bin의 범위를 4도로 만들어서, 히스토그램으로 보여주세요.

# 히스토그램 쓰기위해 hist 함수 사용
# 범위 설정을 위해선 최소값 최대값 확인하여 np.arange 로 범위 설정 필요 해당 변수로 bins 범위를 설정해 줘야함

 

df['최고기온(℃)'].describe()

count    39168.000000
mean        16.684921
std         10.996621
min        -16.300000
25%          7.100000
50%         18.500000
75%         26.200000
max         38.400000
Name: 최고기온(℃), dtype: float64

 

# 최소값과 최대값을 찾았고, 4도로 설정하기로 하였으니, 최대값까지 포함하기위해 +4, 단계도 4로 설정하여 변수로 저장해 준다.

my_bins = np.arange(-16.3, 38.4 +4 , 4)

 

# 해당 변수까지 합쳐서 hist 함수 사용

plt.hist(data= df, x='최고기온(℃)', rwidth=0.9, bins = my_bins)
plt.show()

 

실습 3) 위에서는 모든 날짜에 대한 데이터 입니다.  그러면!

2014년도 부터의 데이터를 기준으로, bin의 범위를 4도로 만들어서, 히스토그램으로 보여주세요.

 

# pandas는 문자열일 경우에도 조건식을 사용 가능

# 이러면 2014년도 1월 1일 이후 데이터만 가지고 온다.


df_2014 = df.loc[df['날짜'] >= '2014-01-01' ,  ]
df_2014

 

# 최소값, 최고값 확인후 bin 변수 생성

df_2014.describe()

 

my_bins = np.arange(-10.7 , 36.6 + 4 , 4)

 

plt.hist(data= df_2014, x='최고기온(℃)', rwidth=0.9, bins = my_bins)
plt.show()

 

실습 4) 2017-08-01 ~ 2017-08-15 사이의 데이터에서,

날짜를 x축, 최고기온을 y축으로 스케터로 나타내세요.

 

# 요청한 데이터 범위로만 데이터를 가공

(df['날짜'] >= '2017-08-01') & (df['날짜'] <= '2017-08-15')

0        False
1        False
2        False
3        False
4        False
         ...  
39921    False
39922    False
39923    False
39924    False
39925    False
Name: 날짜, Length: 39926, dtype: bool

 

# 새로운 변수값으로 저장

df_3 = df.loc[(df['날짜'] >= '2017-08-01') & (df['날짜'] <= '2017-08-15') ,  ]

 

# 기준되는 x값 y값 설정후 plt.scatter() 사용

plt.scatter(data=df_3, x= '날짜' , y='최고기온(℃)')
plt.xticks(rotation = 60)
plt.show()

 

다음 실습문제로 계속

반응형