Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/py-polars/tests/unit/dataframe/test_to_dict.py
6939 views
1
from __future__ import annotations
2
3
from typing import Any
4
5
import pytest
6
from hypothesis import given
7
8
import polars as pl
9
from polars.testing import assert_frame_equal
10
from polars.testing.parametric import dataframes
11
12
13
@given(
14
df=dataframes(
15
excluded_dtypes=[
16
pl.Categorical, # Bug: https://github.com/pola-rs/polars/issues/16196
17
pl.Struct,
18
],
19
# Roundtrip doesn't work with time zones:
20
# https://github.com/pola-rs/polars/issues/16297
21
allow_time_zones=False,
22
)
23
)
24
def test_to_dict(df: pl.DataFrame) -> None:
25
d = df.to_dict(as_series=False)
26
result = pl.from_dict(d, schema=df.schema)
27
assert_frame_equal(df, result, categorical_as_str=True)
28
29
30
@pytest.mark.parametrize(
31
("as_series", "inner_dtype"),
32
[
33
(True, pl.Series),
34
(False, list),
35
],
36
)
37
def test_to_dict_misc(as_series: bool, inner_dtype: Any) -> None:
38
df = pl.DataFrame(
39
{
40
"A": [1, 2, 3, 4, 5],
41
"fruits": ["banana", "banana", "apple", "apple", "banana"],
42
"B": [5, 4, 3, 2, 1],
43
"cars": ["beetle", "audi", "beetle", "beetle", "beetle"],
44
"optional": [28, 300, None, 2, -30],
45
}
46
)
47
s = df.to_dict(as_series=as_series)
48
assert isinstance(s, dict)
49
for v in s.values():
50
assert isinstance(v, inner_dtype)
51
assert len(v) == df.height
52
53