Python/Python For Analytics

[ Python ] csv 파일 읽고, 쓰기 ( pandas / csv 모듈 )

Pydole 2023. 5. 16. 14:08

 

데이터를 처리하다 보면 csv 파일 자주 만나게 되는데, Python pandas와 csv 모듈로 처리할 수 있다.


 

파이썬 pandas csv 파일 읽고, 쓰기

 

샘플데이터 : example.csv (UTF-8)

 

=============================

"Student","Math","Computer","English"

"인호",90,85,100

"철수",85,100,95

"영희",75,70,85

"민수",95,85,90

"지훈",100,85,95

"지영",90,85,90

"정희",95,85,95

=============================

 


 

 

pandas의 read_csv 메소드로 csv 파일 읽기

 

import pandas as pd

df = pd.read_csv(r'C:\Python\SC\example.csv')
print(df)

 

  Student  Math  Computer  English
0      인호    90        85      100
1      철수    85       100       95
2      영희    75        70       85
3      민수    95        85       90
4      지훈   100        85       95
5      지영    90        85       90
6      정희    95        85       95

 

 

names 옵션으로 컬럼명 지정하기

 

import pandas as pd

df = pd.read_csv(r'C:\Python\SC\example.csv', skiprows=[0], names=['학생', '수학', '컴퓨터', '영어'])
print(df)

* sample.csv의 경우 "Student","Math","Computer","English"이 포함되어 있기 때문에, skiprows로 제외

 

 

   학생   수학  컴퓨터   영어
0  인호   90   85  100
1  철수   85  100   95
2  영희   75   70   85
3  민수   95   85   90
4  지훈  100   85   95
5  지영   90   85   90
6  정희   95   85   95

  

 

 

 

pandas의 read_csv 메소드로 export

 

import pandas as pd

df = pd.read_csv(r'C:\Python\SC\example.csv', skiprows=[0], names=['학생', '수학', '컴퓨터', '영어'])
df.to_csv(r'C:\Python\SC\result.csv', index=False)

* index=False : index는 제외

 

 


 

import csv

f = open('sample.csv')
rows = csv.reader(f)
f.close

for row in rows:
    print(row)

 

['Student', 'Math', 'Computer', 'English']
['인호', '90', '85', '100']
['철수', '85', '100', '95']
['영희', '75', '70', '85']
['민수', '95', '85', '90']
['지훈', '100', '85', '95']
['지영', '90', '85', '90']
['정희', '95', '85', '95']