Chalk DataFrames
Scan a local CSV file with an explicit schema and write the result as Parquet.
Create a sample CSV in a temporary directory, then scan it using an Arrow schema. Keep the directory available until the query finishes reading the file.
from pathlib import Path
from tempfile import TemporaryDirectory
import pyarrow as pa
from chalkdf import DataFrame
with TemporaryDirectory() as directory:
path = Path(directory) / "transactions.csv"
path.write_text("user,amount\na,12\na,8\nb,30\n", encoding="utf-8")
schema = pa.schema([("user", pa.string()), ("amount", pa.int64())])
tx = DataFrame.scan([str(path)], name="transactions", schema=schema)
rows = tx.to_arrow()
rows| # | userstring | amountint64 |
|---|---|---|
| 1 | a | 12 |
| 2 | a | 8 |
| 3 | b | 30 |
To save a frame as Parquet, call tx.write_parquet(output_uri_prefix) while its input files are accessible. Supply a directory URI such as file:///tmp/transaction-output for the output files. See SQL for reading from a configured SQL connection.
Write the Arrow rows from the CSV example to a new directory. The output prefix can contain multiple files, so use the Parquet file paths when scanning it.
with TemporaryDirectory() as directory:
output = Path(directory) / "transactions"
DataFrame.from_arrow(rows).write_parquet(output.as_uri())
paths = [str(file) for file in output.rglob("*.parquet")]
saved = DataFrame.scan(paths, name="saved", schema=rows.schema).to_arrow()
saved| # | userstring | amountint64 |
|---|---|---|
| 1 | a | 12 |
| 2 | a | 8 |
| 3 | b | 30 |
Use the same schema when you read the saved files to retain the column types.