본문 바로가기
Data

Parquet 파일 읽고 써보기 | LIM

by forestlim 2023. 2. 4.
728x90
반응형

먼저 Parquet에 대한 개념과 기본 원리에 대한 정리한 글이다. 

https://amazelimi.tistory.com/78

 

Parquet란 무엇이고, 왜 사용하는가

Parquet (파케이) 데이터를 저장하는 방식 중 하나로 하둡생태계에서 많이 사용되는 파일 포맷이다. 빅데이터를 처리할 때는 많은 시간과 비용이 들어가기 때문에 빠르게 읽고, 압축률이 좋아야

amazelimi.tistory.com

 

Parquet 가 왜 압축률이 좋고 빠른지에 대해 알아봤으니 실제로 적용해 보는 일만 남았다.

먼저, Parquet 으로 데이터를 저장하면 좋은 점에 대해 알아보자.

  • Data Type 이 저장된다.
  • 특정 Column 만 선택해서 읽을 수 있다. (Parquet 은 Column-Based File)
  • 용량이. csv로 저장하는 거에 비해 매우 작다 (압축하기 때문)

 

🐍 파이썬 Pandas에서 Parquet 변환하기

Pandas에서 Parquet 변환하는 건 매우 간단하다. 

to_parquet을 사용하여 간단하게 변환할 수 있다. 

 

먼저, 사용법에 대해 간단하게 살펴보면 이러하다. 

import pandas as pd

df = pd.DataFrame({'Birth':['2019-01-01 09:10:00',
                            '2019-01-08 09:20:30',
                            '2019-02-01 10:20:00',
                            '2019-02-02 11:40:50',
                            '2019-02-28 15:10:20',
                            '2019-04-10 19:20:50',
                            '2019-06-30 21:20:50',
                            '2019-07-20 23:30:59'],
                     'Num': [1, 2, 3, 4, 5, 6, 7, 8]})

df['Birth'] = pd.to_datetime(df['Birth'], format='%Y-%m-%d %H:%M:%S', errors='raise')

df.to_parquet('./test.parquet', engine='pyarrow', compression='gzip')

 

1. to_parquet을 사용하기 위해서는 engine 이 필요하다.

    pyarrow와 fastparquet 이 있고 아무것도 설정하지 않으면 기본 auto이다. 

   압축속도는 pyarrow 가 압도적으로 훨씬 높지만 기본적인 자체 라이브러리 용량이 fastparquet의 100배라고 한다. 

 

2. compression (압축기법) 이 필요하다.

   snappy, gzip, brotli 세가지가 존재한다. 다들 찾아보니 snappy 가 설치 도중 문제가 많이 생겨서 gzip을 많이 사용하는 것 같다.

 

3. 마지막으로 저장할 경로를 설정해 주면 끝!

 

🧐 Parquet 파일에 저장되는 데이터 타입은 어떤 게 있을까

이 부분을 제대로 파악하고 있지 못해서 뻘짓을 좀 했었다..

Pandas에서 column dtype을 분명히 datetime64로 진행했는데 계속 Parquet 파일에 TimeStamp로 저장되어 

BigQuery에 Timestamp로 저장되어 UTC로 보이는 문제가 발생했었다. 

 

방법이 있을 것 같아서 한 며칠 삽질 하다가 결국 다른 방법으로 저장했는데

이런.. Parquet에 저장되는 데이터 타입에 datetime 이 없었던 것이다.

 

 

여기에 Parquet Data Type 이 정리되어 있다

https://learn.microsoft.com/en-us/common-data-model/sdk/parquet-to-cdm-datatype

 

Mapping Parquet types to Common Data Model data types - Common Data Model

This article provides assistance to developers in finding the appropriate equivalents of Parquet data types in Common Data Model.

learn.microsoft.com

 

🤓 변환해서 저장했으니 이제 읽어보자

1. pandas를 이용해서 읽을 수 있다.

   pd.read_parquet()

 

2. pyarrow.parquet 모듈을 활용하여 읽을 수 있다.

   pq.read_pandas, pq.read_table -> 동일하다. 

 

3. to_pandas()를 활용하면 dataframe 형태로 보여준다. 
   또한, read_pandas, read_table에 columns를 추가하면 원하는 column 만 읽을 수 있다. 

 

4. pq.read_schema()를 통해 parquet 파일 내 데이터들의 Type을 바로 조회할 수 있다.

 

import pandas as pd
import pyarrow.parquet as pq

df = pd.read_parquet('./test.parquet')
print(df)
print('================================')
df = pq.read_pandas('./test.parquet')
print(df)
print('=================================')
df = pq.read_table('./test.parquet', columns=['Birth']).to_pandas()
print(df)
print('=================================')
schema = pq.read_schema('./test.parquet')
print(schema)


----------------------------------------------------


                Birth  Num
0 2019-01-01 09:10:00    1
1 2019-01-08 09:20:30    2
2 2019-02-01 10:20:00    3
3 2019-02-02 11:40:50    4
4 2019-02-28 15:10:20    5
5 2019-04-10 19:20:50    6
6 2019-06-30 21:20:50    7
7 2019-07-20 23:30:59    8
================================
pyarrow.Table
Birth: timestamp[us]
Num: int64
----
Birth: [[2019-01-01 09:10:00.000000,2019-01-08 09:20:30.000000,2019-02-01 10:20:00.000000,2019-02-02 11:40:50.000000,2019-02-28 15:10:20.000000,2019-04-10 19:20:50.000000,2019-06-30 21:20:50.000000,2019-07-20 23:30:59.000000]]
Num: [[1,2,3,4,5,6,7,8]]
=================================
                Birth
0 2019-01-01 09:10:00
1 2019-01-08 09:20:30
2 2019-02-01 10:20:00
3 2019-02-02 11:40:50
4 2019-02-28 15:10:20
5 2019-04-10 19:20:50
6 2019-06-30 21:20:50
7 2019-07-20 23:30:59
=================================
Birth: timestamp[us]
Num: int64
-- schema metadata --
pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 481

 

늘 써오던 거지만 이번 기회에 제대로 공부할 수 있게 되어서 뿌듯했다. 

 

 

 

📚 참고

https://uiandwe.tistory.com/1322

 

parquet

데이터를 쉽게 접근할 수 있도록 csv로 저장해서 사용한다. 하지만 csv는 메타데이터를 저장할 수 없어 칼럼 별로 dtype을 다시 지정해줘야 하는 일이 생기며, 읽고 쓸 때 시간이 많이 걸린다는 단

uiandwe.tistory.com

https://wesmckinney.com/blog/python-parquet-update/(pyarrow vs fastparquet benchmark)

 

Development update: High speed Apache Parquet in Python with Apache Arrow

Over the last year, I have been working with the Apache Parquet community to build out parquet-cpp, a first class C++ Parquet file reader/writer implementation suitable for use in Python and other data applications. Uwe Korn and I have built the Python int

wesmckinney.com

 

728x90
반응형

댓글