Question

I have several tables of data in separate CSVs. The smallest is 20 MB and the largest is 50 GBs. I need to join across the tables to create one denormalized JSON object.

How should I do it in python?

Comments on question:
  • DataDynamo: Are you able to load the entire dataset into memory or do you need a solution that processes the data in chunks?
  • Pythonista: Do you have a common key across all tables to join them?

Answer 1:

[ 7 upvotes ]
I would recommend using pandas library for this task. You can read the CSV files in chunks and perform the join operation. This way, you won't need to load the entire dataset into memory. Here's a sample approach:

⎗
✓
import pandas as pd

# Define the chunk size
chunksize = 10 ** 6

# Read and process the first file
first_file = "first_file.csv"
first_file_iterator = pd.read_csv(first_file, chunksize=chunksize)
first_chunk = next(first_file_iterator)

# Read and process the second file
second_file = "second_file.csv"
second_file_iterator = pd.read_csv(second_file, chunksize=chunksize)

# Perform the join operation
result = pd.DataFrame()
for second_chunk in second_file_iterator:
    joined_data = first_chunk.merge(second_chunk, on='common_key', how='inner')
    result = result.append(joined_data)

# Save the denormalized JSON object
result.to_json("output.json", orient='records', lines=True)

Note that you might need to adjust the chunksize depending on your system's memory.

Comments on Answer:
  • QuestionAsker: This solution works great for me. Thanks!

Answer 2:

[ 3 upvotes ]
Another solution, especially if you have limited memory, is to use the Dask library. It provides an efficient way to handle large datasets using parallel processing and lazy evaluation. Here's a sample approach:

⎗
✓
import dask.dataframe as dd

# Read the CSV files
first_file = "first_file.csv"
second_file = "second_file.csv"

first_df = dd.read_csv(first_file)
second_df = dd.read_csv(second_file)

# Perform the join operation
result = first_df.merge(second_df, on='common_key', how='inner')

# Save the denormalized JSON object
result.to_json("output/*.json", orient='records', lines=True)

Dask will automatically handle chunking and parallel processing.

Comments on Answer:
  • QuestionAsker: I tried this solution as well and it works good too. I'm going with the first one for now, but I'll keep Dask in mind for future projects. Thanks!
Edit

Pub: 08 May 2023 04:44 UTC

Views: 222