데이터를 처리하다 보면 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']
'Python > Python For Analytics' 카테고리의 다른 글
[ Python ] pandas plot 을 이용한 다양한 graph 그리기 (0) | 2023.05.24 |
---|---|
[ Python ] matplotlib plot Shading Area (특정구간 강조) (0) | 2023.02.03 |
[ Python ] pandas를 이용한 bar graph (stacked) (0) | 2022.03.01 |
[Python] wordcloud 만들기 (0) | 2021.01.28 |
[Python] seaborn을 이용한 간단한 heatmap 그리기 (0) | 2020.11.28 |
[Python] pandas와 pymssql을 이용하여 MSSQL 연동 (0) | 2020.10.05 |
[Python] padnas Dataframe 에서 astype을 이용하여 숫자형으로 변환할 수 없을 때 to_numeric을 이용 (0) | 2020.08.02 |
[Python] matplotlib - 그래프에 값 표시 하기 (1) | 2020.08.02 |