|
| 1 | +# DataFrame and Arrow Compatibility |
| 2 | + |
| 3 | +`perspective-python` accepts a `Table` constructor argument from any of the |
| 4 | +common Python columnar data libraries. In all three cases, `perspective.table` |
| 5 | +(and `Table.update()`) consume the input directly — there is no need to |
| 6 | +serialize to Apache Arrow IPC bytes yourself. However, note is |
| 7 | +still the most efficient way to bulk load data into `Table`. |
| 8 | + |
| 9 | +## PyArrow |
| 10 | + |
| 11 | +```python |
| 12 | +import pyarrow as pa |
| 13 | +import perspective |
| 14 | + |
| 15 | +arrow_table = pa.table({ |
| 16 | + "int": pa.array([1, 2, 3], type=pa.int64()), |
| 17 | + "float": pa.array([1.5, 2.5, 3.5], type=pa.float64()), |
| 18 | + "string": pa.array(["a", "b", "c"], type=pa.string()), |
| 19 | +}) |
| 20 | + |
| 21 | +table = perspective.table(arrow_table) |
| 22 | +``` |
| 23 | + |
| 24 | +The same applies to `Table.update()`: |
| 25 | + |
| 26 | +```python |
| 27 | +table.update(arrow_table) |
| 28 | +``` |
| 29 | + |
| 30 | +If you have Arrow data already in IPC format (e.g. read from disk, received |
| 31 | +over the wire, or produced by another tool), pass the raw `bytes` directly — |
| 32 | +both stream and file formats are auto-detected: |
| 33 | + |
| 34 | +```python |
| 35 | +with open("data.arrow", "rb") as f: |
| 36 | + table = perspective.table(f.read()) |
| 37 | +``` |
| 38 | + |
| 39 | +## Polars |
| 40 | + |
| 41 | +```python |
| 42 | +import polars as pl |
| 43 | +import perspective |
| 44 | + |
| 45 | +df = pl.DataFrame({ |
| 46 | + "a": [1, 2, 3, 4, 5], |
| 47 | + "b": ["x", "y", "z", "x", "y"], |
| 48 | +}) |
| 49 | + |
| 50 | +table = perspective.table(df) |
| 51 | +``` |
| 52 | + |
| 53 | +Internally, the `DataFrame` is converted to a `pyarrow.Table` before |
| 54 | +ingestion, so Polars columns inherit the Arrow type mapping above. |
| 55 | + |
| 56 | +See also Perspective [Virtual Server support for `polars.DataFrame`](./virtual_server/polars.md) |
| 57 | + |
| 58 | +## Pandas |
| 59 | + |
| 60 | +`pandas.DataFrame` is supported via `pyarrow.Table.from_pandas`, which |
| 61 | +dictates behavior including type support — see the |
| 62 | +[pyarrow pandas docs](https://arrow.apache.org/docs/python/pandas.html) for |
| 63 | +details on which pandas dtypes round-trip cleanly. |
| 64 | + |
| 65 | +```python |
| 66 | +from datetime import date, datetime |
| 67 | +import numpy as np |
| 68 | +import pandas as pd |
| 69 | +import perspective |
| 70 | + |
| 71 | +data = pd.DataFrame({ |
| 72 | + "int": np.arange(100), |
| 73 | + "float": [i * 1.5 for i in range(100)], |
| 74 | + "bool": [True for i in range(100)], |
| 75 | + "date": [date.today() for i in range(100)], |
| 76 | + "datetime": [datetime.now() for i in range(100)], |
| 77 | + "string": [str(i) for i in range(100)], |
| 78 | +}) |
| 79 | + |
| 80 | +table = perspective.table(data, index="float") |
| 81 | +``` |
0 commit comments