반응형
파이썬 데이터 읽기
들어가며
- csv, tsv, text 파일을 읽어 판다스(pandas) dataframe으로 읽는 방법이다.
- encoding 문제 해결
- sep을 '\t', ','등 원하는 방법으로
- data의 사이즈가 클 경우이는 split해서 데이터를 읽는다.
- 읽는 동시에 data에서 원하는 column, row만을 filtering 할 수 있다.
코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas | |
def get_df(cols, filename, sep='\t'): | |
iter_csv = pd.read_csv('/home/jslee/' + filename,iterator=True, encoding='utf8', chunksize=1000, sep=sep, names=cols) | |
# df = pd.concat([chunk[chunk['field'] > constant] for chunk in iter_csv]) | |
df = pd.concat([chunk for chunk in iter_csv]) | |
return df | |
get_df(['col1', 'col2', 'col3'], filename, sep='\t') | |
get_df(['col1', 'col2', 'col3'], filename, sep=',') |
반응형
'Programming > Python' 카테고리의 다른 글
파이썬 스케일이 다른 그래프 (0) | 2017.11.02 |
---|---|
파이썬 디렉토리 생성 코드 (0) | 2017.11.02 |
[Python] Flask Response Encoding 문제 (0) | 2017.02.07 |
[Python] Flask logging 하는 방법 (0) | 2017.02.07 |
[Python] Virtualenv 설치 및 dependencies 관리하기 (0) | 2017.02.07 |