DataFusion in Python¶
This is a Python library that binds to Apache Arrow in-memory query engine DataFusion.
Like pyspark, it allows you to build a plan through SQL or a DataFrame API against in-memory data, parquet or CSV files, run it in a multi-threaded environment, and obtain the result back in Python.
It also allows you to use UDFs and UDAFs for complex operations.
The major advantage of this library over other execution engines is that this library achieves zero-copy between Python and its execution engine: there is no cost in using UDFs, UDAFs, and collecting the results to Python apart from having to lock the GIL when running those operations.
Its query engine, DataFusion, is written in Rust, which makes strong assumptions about thread safety and lack of memory leaks.
Technically, zero-copy is achieved via the c data interface.
Install¶
pip install datafusion
Example¶
In [1]: import datafusion
In [2]: from datafusion import col
In [3]: import pyarrow
# create a context
In [4]: ctx = datafusion.SessionContext()
# create a RecordBatch and a new DataFrame from it
In [5]: batch = pyarrow.RecordBatch.from_arrays(
...: [pyarrow.array([1, 2, 3]), pyarrow.array([4, 5, 6])],
...: names=["a", "b"],
...: )
...:
In [6]: df = ctx.create_dataframe([[batch]], name="batch_array")
# create a new statement
In [7]: df = df.select(
...: col("a") + col("b"),
...: col("a") - col("b"),
...: )
...:
In [8]: df
Out[8]:
DataFrame()
+-------------------------------+-------------------------------+
| batch_array.a + batch_array.b | batch_array.a - batch_array.b |
+-------------------------------+-------------------------------+
| 5 | -3 |
| 7 | -3 |
| 9 | -3 |
+-------------------------------+-------------------------------+