728x90
반응형
csv 파일과 pandas로 연계해서 작업할 수 있습니다.
pandas로 데이터를 만듭니다.
import pandas as pd
import numpy as np
# df = pd.DataFrame()
df = pd.DataFrame(columns=range(3)) # 3개 column DataFrame 지정
df.columns = ['model','product_type','cnt'] # column명 지정
# df.index.name = 'idx'
df.set_index(keys=['model']) #
df.loc[len(df)] = ['model001','TV',3]
df.loc[len(df)] = ['model002','TV',1]
df.loc[len(df)] = ['model003','냉장고',3]
df.loc[len(df)] = ['model004','냉장고',5]
df.loc[len(df)] = ['model005','전자레인지',1]
df.loc[len(df)] = ['model006','전자레인지',2]
df

pandas DataFrame을 csv 파일로 저장합니다.
df.to_csv('product.csv')
파일 내용입니다.
,model,product_type,cnt
0,model001,TV,3
1,model002,TV,1
2,model003,냉장고,3
3,model004,냉장고,5
4,model005,전자레인지,1
5,model006,전자레인지,2
csv 파일을 pandas로 읽어 옵니다.
아까 pandas DataFrame으로 만든 동일한 구조와 데이터를 확인할 수 있습니다.
df2 = pd.read_csv('product.csv', index_col=0) # index 없이 읽음
df2

pandas 기능으로 데이터 검색을 할 수 있습니다.
df[(df.model == 'model001')]

df[(df.product_type == 'TV')]

df[(df.product_type == 'TV') | (df.product_type == '냉장고')]

합계 등도 구할 수 있습니다.
df.cnt.sum()

728x90
반응형
'프로그램' 카테고리의 다른 글
[파이썬] 배열에서 항목(중복제거) 찾고 Count 하기 (0) | 2022.09.18 |
---|---|
[파이썬] 폴더내의 파일명 변경 (0) | 2022.09.18 |
[파이썬] pandas DataFrame 컬럼 순서 변경 (0) | 2022.09.16 |
[Rust] 입력 받기, 변수 선언, println (0) | 2022.09.16 |
[Rust] 에러(stream did not contain valid UTF-8) (0) | 2022.09.15 |
댓글