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_glimpse.py
6939 views
1
import textwrap
2
from datetime import datetime
3
from typing import Any
4
5
import polars as pl
6
7
8
def test_glimpse(capsys: Any) -> None:
9
df = pl.DataFrame(
10
{
11
"a": [1.0, 2.8, 3.0],
12
"b": [4, 5, None],
13
"c": [True, False, True],
14
"d": [None, "b", "c"],
15
"e": ["usd", "eur", None],
16
"f": pl.datetime_range(
17
datetime(2023, 1, 1),
18
datetime(2023, 1, 3),
19
"1d",
20
time_unit="us",
21
eager=True,
22
),
23
"g": pl.datetime_range(
24
datetime(2023, 1, 1),
25
datetime(2023, 1, 3),
26
"1d",
27
time_unit="ms",
28
eager=True,
29
),
30
"h": pl.datetime_range(
31
datetime(2023, 1, 1),
32
datetime(2023, 1, 3),
33
"1d",
34
time_unit="ns",
35
eager=True,
36
),
37
"i": [[5, 6], [3, 4], [9, 8]],
38
"j": [[5.0, 6.0], [3.0, 4.0], [9.0, 8.0]],
39
"k": [["A", "a"], ["B", "b"], ["C", "c"]],
40
}
41
)
42
result = df.glimpse(return_as_string=True)
43
44
expected = textwrap.dedent(
45
"""\
46
Rows: 3
47
Columns: 11
48
$ a <f64> 1.0, 2.8, 3.0
49
$ b <i64> 4, 5, None
50
$ c <bool> True, False, True
51
$ d <str> None, 'b', 'c'
52
$ e <str> 'usd', 'eur', None
53
$ f <datetime[μs]> 2023-01-01 00:00:00, 2023-01-02 00:00:00, 2023-01-03 00:00:00
54
$ g <datetime[ms]> 2023-01-01 00:00:00, 2023-01-02 00:00:00, 2023-01-03 00:00:00
55
$ h <datetime[ns]> 2023-01-01 00:00:00, 2023-01-02 00:00:00, 2023-01-03 00:00:00
56
$ i <list[i64]> [5, 6], [3, 4], [9, 8]
57
$ j <list[f64]> [5.0, 6.0], [3.0, 4.0], [9.0, 8.0]
58
$ k <list[str]> ['A', 'a'], ['B', 'b'], ['C', 'c']
59
"""
60
)
61
assert result == expected
62
63
# the default is to print to the console
64
df.glimpse()
65
# remove the last newline on the capsys
66
assert capsys.readouterr().out[:-1] == expected
67
68
colc = "a" * 96
69
df = pl.DataFrame({colc: [11, 22, 33, 44, 55, 66]})
70
result = df.glimpse(
71
return_as_string=True, max_colname_length=20, max_items_per_column=4
72
)
73
expected = textwrap.dedent(
74
"""\
75
Rows: 6
76
Columns: 1
77
$ aaaaaaaaaaaaaaaaaaa… <i64> 11, 22, 33, 44
78
"""
79
)
80
assert result == expected
81
82
83
def test_glimpse_colname_length() -> None:
84
df = pl.DataFrame({"a" * 100: [1, 2, 3]})
85
result = df.glimpse(max_colname_length=96, return_as_string=True)
86
87
expected = f"$ {'a' * 95}… <i64> 1, 2, 3"
88
assert result.strip().split("\n")[-1] == expected
89
90