포스팅할게
산더미인데
실습이 많아져
쌓아만 놓고 있습니다!!
하루가 더 길었으면 좋겠습니다.
이번엔 csv 파일이 뭔지를 설명하고
pandas 패키지를 이용해 데이터 전처리와
csv 가져오기, 내보내기를 해보겠습니다.
1. csv 파일이란?
Comma Seperated Value.
쉼표로 구분된 데이터입니다.
(이 한 라인이 각 행, 즉 한 묶음의 데이터가 됩니다.)
csv를 확인할 수 있는 방법은 많겠지만
저는 Visual Studio Code 의 확장 프로그램 중
Rainbow CSV와 Edit csv 를 깔아서
vscode에서 확인해 주었습니다.
2. csv 파일 불러오고 전처리하기
csv나 파일을 읽어오거나 저장해주는 특화된 패키지가 있습니다.
pandas인데요.
" All classes and functions exposed in pandas.* namespace are public. "
documentation 을 살펴보니 pandas만 import하면
모든 class 를 사용해줄 수 있습니다.
https://pandas.pydata.org/docs/reference/index.html#api
API reference — pandas 2.1.4 documentation
This page gives an overview of all public pandas objects, functions and methods. All classes and functions exposed in pandas.* namespace are public. The following subpackages are public. In addition, public functions in pandas.io and pandas.tseries submodu
pandas.pydata.org
다재다능 데이터 분석 패키지입니다.
요 패키지를 사용해서
1. csv 파일을 불러옴
2. 인덱스 제거
3. 결측치 확인
3. 열 삭제
등을 해주면서 데이터 전처리를 해보겠습니다.
먼저 판다쓰를
import 해주겠습니다.
import pandas as pd
저같은 경우 kaggle에서 데이터를 받아와서
C:/_data/kaggle/bike/의 폴더에
"train.csv"
"test.csv"
"sampleSubmission.csv"
라는 파일로 저장해주었는데요.
이 경로를 pd.resd_csv()함수로 입력해주면 끝입니다.
#csv 가져오기
path = 'C:/_data/kaggle/bike/'
train_csv = pd.read_csv(path + "train.csv")
test_csv = pd.read_csv(path + "test.csv")
sampleSubmission_csv = pd.read_csv(path + "sampleSubmission.csv")
제가 불러오 데이터 중 하나인데요, datetime 이라는
인덱스 역할을 하는 컬럼을 제거하고 싶었습니다.
이 경우에는 뒤에 index_col= "컬럼명", 혹은 index_col= 0(컬럼 인덱스)를 써주면
인덱스를 배제하고 데이터를 가져올 수 있습니다,
train_csv = pd.read_csv(path + "train.csv", index_col=0)
이때 train_csv에 저장되는 데이터는 DataFrame이라는
pandas 에서 제공하는 클래스형태가 됩니다.
우리는 이 클래스로 아래의 도큐먼트에
나열된 모든 데이터를 다루는 함수를 사용할 수 있습니다!
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html
pandas.DataFrame — pandas 2.1.4 documentation
Dict can contain Series, arrays, constants, dataclass or list-like objects. If data is a dict, column order follows insertion-order. If a dict contains Series which have an index defined, it is aligned by its index. This alignment also occurs if data is a
pandas.pydata.org
아래와같이 shape, colums, head()등의 함수로
데이터 구조도 확인할 수 있구요.
#데이터 구성 확인
print(train_csv.shape)#(10886, 12)
print(test_csv.shape)#(6493, 9)
print(sampleSubmission_csv.shape)#(6493, 2)
print(train_csv.columns)
'''
Index(['datetime', 'season', 'holiday', 'workingday', 'weather', 'temp',
'atemp', 'humidity', 'windspeed', 'casual', 'registered', 'count'],
dtype='object')
'''
print(test_csv.columns)
'''
Index(['datetime', 'season', 'holiday', 'workingday', 'weather', 'temp',
'atemp', 'humidity', 'windspeed'],
dtype='object')
'''
print(sampleSubmission_csv.columns)
'''
Index(['datetime', 'count'], dtype='object')
'''
print(train_csv.head(15))
print(test_csv.head(15))
print(sampleSubmission_csv.head(15))
isna()로 결측치를 확인하거나
sum()으로 결측치의 개수를 확인할 수도 있고
만약 결측치가 있다면 fillna() 함수로 채워줄 수도 있습니다.
mean()함수를 호출해서 평균을 채워줄 수도 있죠.
#결측치 확인
print("결측치")
print(train_csv.isna().sum())#결측치 없음
print(test_csv.isna().sum())#결측치 없음
#만약 결측치가 있다면
train_csv.fillna(0) #0
train_csv.fillna(train_csv.mean()) #평균
drop()함수를 이용해서 열을 지울 수도 있습니다.
딕셔너리 같이 DataFrame에서는 train_csv['열이름'] 으로
해당 열의 데이터를 가져올 수도 있습니다.
#train_csv / casual registered 제거
x = train_csv.drop('count', axis=1).drop('casual', axis=1).drop('registered', axis=1)
print(x)
#count 분리
y = train_csv['count']
3. csv 내보내기
모델이 예측한 결과값을
sampleSubmission.csv의 count 열로 담아서 내보내는 코드입니다.
먼저 submission이라는 결과를
sampleSubmission_csv DataFrame의 'count' 열에 채워넣고
to_csv() 함수를 사용하면 내보내기 완료입니다.
앞에 입력한것은 파일경로이구
default값으로 index를 붙여줘서
저는 False로 index붙임 없이 파일을 내보냈습니다.
#내보내기
sampleSubmission_csv['count'] = submission
sampleSubmission_csv.to_csv(path + "sampleSubmission_0108.csv", index=False)
이렇게 데이터 전저리에
엄청 유용한
pandas 패키지와
패키지의 read_csv() 함수,
DataFrame 클래스의
여러 함수와 to_csv()함수를 사용해서
csv 형식의 파일를 데이터화 해서 다뤄보았습니다.
틀린점이 있다면 지적해주세요!.
'인공지능 개발하기 > Machine Learning' 카테고리의 다른 글
[Tensorflow] 15. 선형회귀 평가방식(MSE, MAE, RMSE) (1) | 2024.01.13 |
---|---|
[Tensorflow] 14. 데이콘(Dacon) 연습 대회 참가하기 (2) | 2024.01.09 |
[Tensorflow] 12. 연습용 데이터 사용해보기 Scikit Learn datasets (1) | 2024.01.07 |
[Tensorflow] 11. 결정계수(R2) - Scikit Learn r2_score (0) | 2024.01.05 |
[Tensorflow] 10. 모델 훈련 결과 시각화 하기 (feat. matplolib) (0) | 2024.01.04 |