7

I want to write a Python extension using Rust with Ctypes or Pyo3 to get better performance than native Python. But how to exchange data such as Polars DataFrame or ndarray type between Rust and Python?

4
  • 1
    See: github.com/pola-rs/polars/tree/master/examples/… Commented Mar 16, 2022 at 12:17
  • Thanks for reply, I noticed that fn array_to_rust in the example has a comment /// Take an arrow array from python and convert it to a rust arrow array. , so is this means the other three func will copy data? If the data from rust is used to create a DataFrame, is rust_series_to_py_series more efficient? Commented Mar 16, 2022 at 13:23
  • See: stackoverflow.com/questions/75292316/… Commented Apr 17, 2023 at 18:54
  • And: medium.com/@niklas.molin/… Commented Apr 17, 2023 at 18:54

1 Answer 1

1

The easiest way to have Rust and Python work together with Polars is via the official pyo3-polars crate. You make your crate using PyO3 as usual, and when you want to pass a Series, DataFrame or LazyFrame, you pass pyo3_polars::PySeries, pyo3_polars::PyDataFrame and pyo3_polars::PyLazyFrame respectively. They all have one public field with the Rust Polars type which makes it very easy to convert between them and the Polars type, but they are also convertible from/to Python Polars objects with PyO3.

If you want to extend Polars using user-defined functions, make sure to read about expression plugins. They are the most efficient way to do that.

ndarray is not easily convertible to Python objects since it was not designed with Python interoperability in mind, but you can use the numpy crate. It gives you access to Numpy arrays (creation and convertion), and can show them (with zero copy!) as ndarray views.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.