본문 바로가기

Data&Processing

Convert Pandas with MapType Value to Pyarrow

  • Pandas MapType column을 pyarrow로 변환했을때 default 로 struct type으로 변환이되며
  • Hive 테이블을 동일하게 Map Type으로 설정하면 Hive에서 해당컬럼데이터를 못 읽음.
  • 꼭 Map Type으로 변환하고 싶다면 다음과 같이
    1. schema을 설정해서 파라메터로 추가하고
    2. MapType 컬럼은 Tuple로 변환함
d = {'conditions': [{"b":"1","aa":"22"},{"1":"22"}]}
df1 = pd.DataFrame(data=d)

pyarrow.Table.from_pandas(df1, preserve_index=False)
pyarrow.Table
conditions: struct<1: string, aa: string, b: string>
  child 0, 1: string
  child 1, aa: string
  child 2, b: string

# struct로 변환이 되면 Hive Table이 Map Type일 경우 컬럼데이터 못읽음
pa.Table.from_pandas(df1, schema=schema1, preserve_index=False)
# python MapType을 pyarrow schema 에 MapType으로 변경이 안됨
# pandas map을 tuple로 변경 후 pyarrow로 변환해야함

d = {'conditions': [[("b","1"),("aa","22")],[("1","22")]]}
df1 = pd.DataFrame(data=d)

schema1 = pa.schema([
('conditions', pa.map_(pa.string(), pa.string()))
])

pa.Table.from_pandas(df1, schema=schema1, preserve_index=False)
# works!!!