ℕʘʘḆḽḘ
ℕʘʘḆḽḘ

Reputation: 19375

how to efficiently split a large dataframe into many parquet files?

Consider the following dataframe

import pandas as pd
import numpy as np
import pyarrow.parquet as pq
import pyarrow as pa

idx = pd.date_range('2017-01-01 12:00:00.000', '2017-03-01 12:00:00.000', freq = 'T')

dataframe = pd.DataFrame({'numeric_col' : np.random.rand(len(idx)),
                          'string_col' : pd.util.testing.rands_array(8,len(idx))},
                           index = idx)

dataframe
Out[30]: 
                     numeric_col string_col
2017-01-01 12:00:00       0.4069   wWw62tq6
2017-01-01 12:01:00       0.2050   SleB4f6K
2017-01-01 12:02:00       0.5180   cXBvEXdh
2017-01-01 12:03:00       0.3069   r9kYsJQC
2017-01-01 12:04:00       0.3571   F2JjUGgO
2017-01-01 12:05:00       0.3170   8FPC4Pgz
2017-01-01 12:06:00       0.9454   ybeNnZGV
2017-01-01 12:07:00       0.3353   zSLtYPWF
2017-01-01 12:08:00       0.8510   tDZJrdMM
2017-01-01 12:09:00       0.4948   S1Rm2Sqb
2017-01-01 12:10:00       0.0279   TKtmys86
2017-01-01 12:11:00       0.5709   ww0Pe1cf
2017-01-01 12:12:00       0.8274   b07wKPsR
2017-01-01 12:13:00       0.3848   9vKTq3M3
2017-01-01 12:14:00       0.6579   crYxFvlI
2017-01-01 12:15:00       0.6568   yGUnCW6n

I need to write this dataframe into many parquet files. Of course, the following works:

table = pa.Table.from_pandas(dataframe)
pq.write_table(table, '\\\\mypath\\dataframe.parquet', flavor ='spark')

My issue is that the resulting (single) parquet file gets too big.

How can I efficiently (memory-wise, speed-wise) split the writing into daily parquet files (and keep the spark flavor)? These daily files will be easier to read in parallel with spark later on.

Thanks!

Upvotes: 9

Views: 8829

Answers (2)

rpanai
rpanai

Reputation: 13437

The solution presented by David doesn't solve the problem as it generates a parquet file for every index. But this slight modified version does the trick

import pandas as pd
import numpy as np
import pyarrow.parquet as pq
import pyarrow as pa
idx = pd.date_range('2017-01-01 12:00:00.000', '2017-03-01 12:00:00.000',
                    freq='T')

df = pd.DataFrame({'numeric_col': np.random.rand(len(idx)),
                   'string_col': pd.util.testing.rands_array(8,len(idx))},
                  index = idx)

df["dt"] = df.index
df["dt"] = df["dt"].dt.date
table = pa.Table.from_pandas(df)
pq.write_to_dataset(table, root_path='dataset_name', partition_cols=['dt'], 
                    flavor='spark')

Upvotes: 2

David
David

Reputation: 11573

Making a string columndt based off of the index will then allow you to write out the data partitioned by date by running

pq.write_to_dataset(table, root_path='dataset_name', partition_cols=['dt'], flavor ='spark')

Answer is based off of this source (note, the source incorrectly lists the partition argument as partition_columns)

Upvotes: 7

Related Questions