이번 포스팅에서는 pyspark에서 pandas API를 거의 그대로 사용할 수 있도록 지원하는 koalas를 알아보고, pandas와 비교하면서 확인하는 과정을 진행.

이 포스팅의 코드는 CloudBreadPaPa/pyspark-koalas: pyspark and koalas dev test repo (github.com) 에서 전체 확인 가능.

 

Apache Spark, koalas와 pandas dataframe

- koalas란 무엇인가?

- koalas 설치

- koalas dataframe 생성 관리

  - koalas Series 생성

  - koalas dataframe 생성

  - pandas dataframe을 koalas dataframe으로 변환
  - pandas dataframe을 spark dataframe으로 변환
  - PySpark dataframe을 koalas dataframe으로 변환

- Spark의 구성 지원 - Apache Arrow 최적화

- plotting

- CSV, Parquet, ORC datasource

 

 

koalas란 무엇인가?

 

The Koalas project makes data scientists more productive when interacting with big data, by implementing the pandas DataFrame API on top of Apache Spark. pandas is the de facto standard (single-node) DataFrame implementation in Python, while Spark is the de facto standard for big data processing. With this package, you can:

Koalas: pandas API on Apache Spark — Koalas 1.8.1 documentation

koalas는 pandas의 DataFrame API를 Apache Spark에서 구현하여, 데이터 과학자들이 빅데이터를 좀더 생산적이로 인터렉티브 하게 사용할 수 있도록 지원하는 프로젝트이다.

 

pandas와 거의 유사한 수준까지 지원해, pandas에 익숙하다면, spark에서도 손쉽고 빠르게 데이터를 처리해 머신러닝 트레이닝이나 개발에 사용할 수 있다.

 

koalas 설치

conda 또는 pip 등으로 설치 가능하다. bash의 conda 환경에서 아래 명령으로 koalas를 설치 가능하며, pip나 source로 설치도 가능하다. 아래 링크에서 관련 내용을 볼 수 있다.

Installation — Koalas 1.8.1 documentation

 

conda 설치 명령

conda install -c conda-forge koalas

 

 

koalas dataframe 생성 관리

koalas Series 생성

import pandas as pd
import numpy as np
import databricks.koalas as ks
from pyspark.sql import SparkSession

# koalas series 생성
s = ks.Series([1, 3, 5, np.nan, 6, 8])
s

결과

0    1.0
1    3.0
2    5.0
3    NaN
4    6.0
5    8.0
dtype: float64

 

pandas의 Series와 같이 koalas에서도 처리된다.

 

koalas DataFrame 생성

# dataframe 생성
kdf = ks.DataFrame(
    {'a': [1, 2, 3, 4, 5, 6],
     'b': [100, 200, 300, 400, 500, 600],
     'c': ["one", "two", "three", "four", "five", "six"]},
    index=[10, 20, 30, 40, 50, 60])
kdf

 

결과

    a    b    c
10    1    100    one
20    2    200    two
30    3    300    three
40    4    400    four
50    5    500    five
60    6    600    six

 

관심 많은 부분, dataframe 부분이다. 그대로 표시되고, dataframe의 여러 API들을 그대로 이용 가능하다.

 

pandas dataframe을 koalas dataframe으로 변환

kdf = ks.from_pandas(pdf)
type(kdf)

결과

databricks.koalas.frame.DataFrame

이렇게, pandas dataframe을 koalas로 변환 가능하다.

 

pandas dataframe을 spark dataframe으로 변환

# pandas dataframe 생성
dates = pd.date_range('20130101', periods=6)
pdf = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))

# spark dataframe 생성
spark = SparkSession.builder.getOrCreate()
sdf = spark.createDataFrame(pdf) # pandas dataframe에서 spark dataframe 생성
sdf.show()

결과

+-------------------+-------------------+--------------------+--------------------+
|                  A|                  B|                   C|                   D|
+-------------------+-------------------+--------------------+--------------------+
|-0.8995092403989157|-1.0433604559785068| 0.30299355959208213|  0.3343467712758245|
|-1.0227280371452447|-0.6964055267165885|  1.7395920025130927|  0.8654688982906457|
|0.06133749500094574|-1.6679265778423085|  1.8346105456449975|  -1.255831880699768|
| 0.3872417901078762| -0.625278731388213|-0.49576694437332197|-0.26623070583298336|
|-1.0416191607623744| 1.4656660471591791|   -1.68602060882246|  0.7231152569838423|
|  0.731511932886863|-0.5647318343228765|  -0.836790224457519|  -0.545040194803223|
+-------------------+-------------------+--------------------+--------------------+

PySpark의 dataframe과 koalas의 dataframe간 트랜스폼이 가능해, 필요한 작업을 취사 선택하고, 데이터의 호환을 유지한다.

 

PySpark dataframe을 koalas dataframe으로 변환

kdf = sdf.to_koalas() 
kdf

마찬가지로, PySpark dataframe을 koalas로도 변환 가능하다.

 

Spark의 구성 지원 - Apache Arrow 최적화

여러 PySpark의 설정을 사용 가능해, 성능을 높이는 코드로 구현 가능하다.

예를 들어, Apache Arrow 최적화를 지원하여, pandas conversion시 속도를 높일 수 있다.

prev = spark.conf.get("spark.sql.execution.arrow.enabled")  # Keep its default value.
ks.set_option("compute.default_index_type", "distributed")  # Use default index prevent overhead.

# arrow.enabled - True 성능
spark.conf.set("spark.sql.execution.arrow.enabled", True)
%timeit ks.range(300000).to_pandas()

# arrow.enabled - False 성능
spark.conf.set("spark.sql.execution.arrow.enabled", False)
%timeit ks.range(300000).to_pandas()

 

 

Plot 기능 제공

# pip install plotly
pdf = pd.DataFrame(np.random.randn(1000, 4), index=pser.index,
                   columns=['A', 'B', 'C', 'D'])
kdf = ks.from_pandas(pdf)
kdf = kdf.cummax()
kdf.plot()

 

koalas.png

pandas의 plot 기능을 유사하게 사용 가능하다.

 

Dataframe을 CSV 파일로 입출력

kdf.to_csv('foo.csv')
ks.read_csv('foo.csv').head(10)

 

Parquet 파일 입출력

kdf.to_parquet('bar.parquet')
ks.read_parquet('bar.parquet').head(10)

 

Spark의 ORC datasource 지원

kdf.to_spark_io('zoo.orc', format="orc")
ks.read_spark_io('zoo.orc', format="orc").head(10)

 

이렇게 다양한 포맷으로 입출력을 지원해 Spark의 기능과 pandas의 장점을 취사 선택 가능하다.

koalas를 이용해 검토하는 일들이 있어서 정리하였다.

 

참고링크

CloudBreadPaPa/pyspark-koalas: pyspark and koalas dev test repo (github.com)

개발자 커뮤니티 SQLER.com - Apache Spark, pyspark 설치 후 jupyter notebook 실행

10 minutes to Koalas — Koalas 1.8.1 documentation

Will Koalas replace PySpark? — Advancing Analytics

databricks/koalas: Koalas: pandas API on Apache Spark (github.com)






XE Login