-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathfunctions.py
More file actions
1802 lines (1565 loc) · 68.6 KB
/
functions.py
File metadata and controls
1802 lines (1565 loc) · 68.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import platform
import sys
from collections.abc import Iterable, Mapping, Sequence
from typing import TYPE_CHECKING, Any
from narwhals._expression_parsing import ExprKind, ExprNode, is_expr, is_series
from narwhals._utils import (
Implementation,
Version,
deprecate_native_namespace,
flatten,
is_eager_allowed,
is_nested_literal,
is_sequence_but_not_str,
normalize_path,
supports_arrow_c_stream,
validate_laziness,
)
from narwhals.dependencies import (
is_narwhals_series,
is_numpy_array,
is_numpy_array_2d,
is_pyarrow_table,
)
from narwhals.exceptions import InvalidOperationError
from narwhals.expr import Expr
from narwhals.translate import from_native, to_native
if TYPE_CHECKING:
from types import ModuleType
from typing_extensions import TypeAlias, TypeIs
from narwhals._native import NativeDataFrame, NativeLazyFrame, NativeSeries
from narwhals._translate import IntoArrowTable
from narwhals._typing import Backend, EagerAllowed, IntoBackend
from narwhals.dataframe import DataFrame, LazyFrame
from narwhals.dtypes import DType
from narwhals.series import Series
from narwhals.typing import (
ConcatMethod,
FileSource,
FrameT,
IntoDType,
IntoExpr,
IntoSchema,
NonNestedLiteral,
PythonLiteral,
_2DArray,
)
_IntoSchema: TypeAlias = "IntoSchema | Sequence[str] | None"
def concat(items: Iterable[FrameT], *, how: ConcatMethod = "vertical") -> FrameT:
"""Concatenate multiple DataFrames, LazyFrames into a single entity.
Arguments:
items: DataFrames, LazyFrames to concatenate.
how: concatenating strategy
- vertical: Concatenate vertically. Column names must match.
- horizontal: Concatenate horizontally. If lengths don't match, then
missing rows are filled with null values. This is only supported
when all inputs are (eager) DataFrames.
- diagonal: Finds a union between the column schemas and fills missing column
values with null.
Raises:
TypeError: The items to concatenate should either all be eager, or all lazy
Examples:
Let's take an example of vertical concatenation:
>>> import pandas as pd
>>> import polars as pl
>>> import pyarrow as pa
>>> import narwhals as nw
Let's look at one case a for vertical concatenation (pandas backed):
>>> df_pd_1 = nw.from_native(pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}))
>>> df_pd_2 = nw.from_native(pd.DataFrame({"a": [5, 2], "b": [1, 4]}))
>>> nw.concat([df_pd_1, df_pd_2], how="vertical")
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| a b |
| 0 1 4 |
| 1 2 5 |
| 2 3 6 |
| 0 5 1 |
| 1 2 4 |
└──────────────────┘
Let's look at one case a for horizontal concatenation (polars backed):
>>> df_pl_1 = nw.from_native(pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}))
>>> df_pl_2 = nw.from_native(pl.DataFrame({"c": [5, 2], "d": [1, 4]}))
>>> nw.concat([df_pl_1, df_pl_2], how="horizontal")
┌───────────────────────────┐
| Narwhals DataFrame |
|---------------------------|
|shape: (3, 4) |
|┌─────┬─────┬──────┬──────┐|
|│ a ┆ b ┆ c ┆ d │|
|│ --- ┆ --- ┆ --- ┆ --- │|
|│ i64 ┆ i64 ┆ i64 ┆ i64 │|
|╞═════╪═════╪══════╪══════╡|
|│ 1 ┆ 4 ┆ 5 ┆ 1 │|
|│ 2 ┆ 5 ┆ 2 ┆ 4 │|
|│ 3 ┆ 6 ┆ null ┆ null │|
|└─────┴─────┴──────┴──────┘|
└───────────────────────────┘
Let's look at one case a for diagonal concatenation (pyarrow backed):
>>> df_pa_1 = nw.from_native(pa.table({"a": [1, 2], "b": [3.5, 4.5]}))
>>> df_pa_2 = nw.from_native(pa.table({"a": [3, 4], "z": ["x", "y"]}))
>>> nw.concat([df_pa_1, df_pa_2], how="diagonal")
┌──────────────────────────┐
| Narwhals DataFrame |
|--------------------------|
|pyarrow.Table |
|a: int64 |
|b: double |
|z: string |
|---- |
|a: [[1,2],[3,4]] |
|b: [[3.5,4.5],[null,null]]|
|z: [[null,null],["x","y"]]|
└──────────────────────────┘
"""
from narwhals.dependencies import is_narwhals_lazyframe
if not items:
msg = "No items to concatenate."
raise ValueError(msg)
items = tuple(items)
validate_laziness(items)
if how not in {"horizontal", "vertical", "diagonal"}: # pragma: no cover
msg = "Only vertical, horizontal and diagonal concatenations are supported."
raise NotImplementedError(msg)
first_item = items[0]
if is_narwhals_lazyframe(first_item) and how == "horizontal":
msg = (
"Horizontal concatenation is not supported for LazyFrames.\n\n"
"Hint: you may want to use `join` instead."
)
raise InvalidOperationError(msg)
plx = first_item.__narwhals_namespace__()
return first_item._with_compliant(
plx.concat([df._compliant_frame for df in items], how=how)
)
def new_series(
name: str,
values: Any,
dtype: IntoDType | None = None,
*,
backend: IntoBackend[EagerAllowed],
) -> Series[Any]:
"""Instantiate Narwhals Series from iterable (e.g. list or array).
Arguments:
name: Name of resulting Series.
values: Values of make Series from.
dtype: (Narwhals) dtype. If not provided, the native library
may auto-infer it from `values`.
backend: specifies which eager backend instantiate to.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN` or `CUDF`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>>
>>> values = [4, 1, 2, 3]
>>> nw.new_series(name="a", values=values, dtype=nw.Int32, backend=pd)
┌─────────────────────┐
| Narwhals Series |
|---------------------|
|0 4 |
|1 1 |
|2 2 |
|3 3 |
|Name: a, dtype: int32|
└─────────────────────┘
"""
return _new_series_impl(name, values, dtype, backend=backend)
def _new_series_impl(
name: str,
values: Any,
dtype: IntoDType | None = None,
*,
backend: IntoBackend[EagerAllowed],
) -> Series[Any]:
implementation = Implementation.from_backend(backend)
if is_eager_allowed(implementation):
ns = Version.MAIN.namespace.from_backend(implementation).compliant
series = ns._series.from_iterable(values, name=name, context=ns, dtype=dtype)
return series.to_narwhals()
if implementation is Implementation.UNKNOWN: # pragma: no cover
_native_namespace = implementation.to_native_namespace()
try:
native_series: NativeSeries = _native_namespace.new_series(
name, values, dtype
)
return from_native(native_series, series_only=True).alias(name)
except AttributeError as e:
msg = "Unknown namespace is expected to implement `new_series` constructor."
raise AttributeError(msg) from e
msg = (
f"{implementation} support in Narwhals is lazy-only, but `new_series` is an eager-only function.\n\n"
"Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n"
f" nw.new_series('a', [1,2,3], backend='pyarrow').to_frame().lazy('{implementation}')"
)
raise ValueError(msg)
@deprecate_native_namespace(warn_version="1.26.0")
def from_dict(
data: Mapping[str, Any],
schema: IntoSchema | Mapping[str, DType | None] | None = None,
*,
backend: IntoBackend[EagerAllowed] | None = None,
native_namespace: ModuleType | None = None, # noqa: ARG001
) -> DataFrame[Any]:
"""Instantiate DataFrame from dictionary.
Indexes (if present, for pandas-like backends) are aligned following
the [left-hand-rule](../concepts/pandas_index.md/).
Notes:
For pandas-like dataframes, conversion to schema is applied after dataframe
creation.
Arguments:
data: Dictionary to create DataFrame from.
schema: The DataFrame schema as Schema or dict of {name: type}. If not
specified, the schema will be inferred by the native library. If
any `dtype` is `None`, the data type for that column will be inferred
by the native library.
backend: specifies which eager backend instantiate to. Only
necessary if inputs are not Narwhals Series.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN` or `CUDF`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
native_namespace: deprecated, same as `backend`.
Examples:
>>> import pandas as pd
>>> import narwhals as nw
>>> data = {"c": [5, 2], "d": [1, 4]}
>>> nw.from_dict(data, backend="pandas")
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| c d |
| 0 5 1 |
| 1 2 4 |
└──────────────────┘
"""
if backend is None:
data, backend = _from_dict_no_backend(data)
if schema and data and (diff := set(schema.keys()).symmetric_difference(data.keys())):
msg = f"Keys in `schema` and `data` are expected to match, found unmatched keys: {diff}"
raise InvalidOperationError(msg)
implementation = Implementation.from_backend(backend)
if is_eager_allowed(implementation):
ns = Version.MAIN.namespace.from_backend(implementation).compliant
return ns._dataframe.from_dict(data, schema=schema, context=ns).to_narwhals()
if implementation is Implementation.UNKNOWN: # pragma: no cover
_native_namespace = implementation.to_native_namespace()
try:
# implementation is UNKNOWN, Narwhals extension using this feature should
# implement `from_dict` function in the top-level namespace.
native_frame: NativeDataFrame = _native_namespace.from_dict(
data, schema=schema
)
except AttributeError as e:
msg = "Unknown namespace is expected to implement `from_dict` function."
raise AttributeError(msg) from e
return from_native(native_frame, eager_only=True)
msg = (
f"{implementation} support in Narwhals is lazy-only, but `from_dict` is an eager-only function.\n\n"
"Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n"
f" nw.from_dict({{'a': [1, 2]}}, backend='pyarrow').lazy('{implementation}')"
)
raise ValueError(msg)
def _from_dict_no_backend(
data: Mapping[str, Series[Any] | Any], /
) -> tuple[dict[str, Series[Any] | Any], ModuleType]:
for val in data.values():
if is_narwhals_series(val):
native_namespace = val.__native_namespace__()
break
else:
msg = "Calling `from_dict` without `backend` is only supported if all input values are already Narwhals Series"
raise TypeError(msg)
data = {key: to_native(value, pass_through=True) for key, value in data.items()}
return data, native_namespace
def from_dicts(
data: Sequence[Mapping[str, Any]],
schema: IntoSchema | Mapping[str, DType | None] | None = None,
*,
backend: IntoBackend[EagerAllowed],
) -> DataFrame[Any]:
"""Instantiate DataFrame from a sequence of dictionaries representing rows.
Notes:
For pandas-like dataframes, conversion to schema is applied after dataframe
creation.
Arguments:
data: Sequence with dictionaries mapping column name to value.
schema: The DataFrame schema as Schema or dict of {name: type}. If not
specified, the schema will be inferred by the native library. If
any `dtype` is `None`, the data type for that column will be inferred
by the native library.
backend: Specifies which eager backend instantiate to.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN` or `CUDF`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
Tip:
If you expect non-uniform keys in `data`, consider passing `schema` for
more consistent results, as **inference varies between backends**:
- pandas uses all rows
- polars uses the first 100 rows
- pyarrow uses only the first row
Examples:
>>> import polars as pl
>>> import narwhals as nw
>>> data = [
... {"item": "apple", "weight": 80, "price": 0.60},
... {"item": "egg", "weight": 55, "price": 0.40},
... ]
>>> nw.DataFrame.from_dicts(data, backend="polars")
┌──────────────────────────┐
| Narwhals DataFrame |
|--------------------------|
|shape: (2, 3) |
|┌───────┬────────┬───────┐|
|│ item ┆ weight ┆ price │|
|│ --- ┆ --- ┆ --- │|
|│ str ┆ i64 ┆ f64 │|
|╞═══════╪════════╪═══════╡|
|│ apple ┆ 80 ┆ 0.6 │|
|│ egg ┆ 55 ┆ 0.4 │|
|└───────┴────────┴───────┘|
└──────────────────────────┘
"""
return Version.MAIN.dataframe.from_dicts(data, schema, backend=backend)
def from_numpy(
data: _2DArray,
schema: IntoSchema | Sequence[str] | None = None,
*,
backend: IntoBackend[EagerAllowed],
) -> DataFrame[Any]:
"""Construct a DataFrame from a NumPy ndarray.
Notes:
Only row orientation is currently supported.
For pandas-like dataframes, conversion to schema is applied after dataframe
creation.
Arguments:
data: Two-dimensional data represented as a NumPy ndarray.
schema: The DataFrame schema as Schema, dict of {name: type}, or a sequence of str.
backend: specifies which eager backend instantiate to.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN` or `CUDF`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
Examples:
>>> import numpy as np
>>> import pyarrow as pa
>>> import narwhals as nw
>>>
>>> arr = np.array([[5, 2, 1], [1, 4, 3]])
>>> schema = {"c": nw.Int16(), "d": nw.Float32(), "e": nw.Int8()}
>>> nw.from_numpy(arr, schema=schema, backend="pyarrow")
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| pyarrow.Table |
| c: int16 |
| d: float |
| e: int8 |
| ---- |
| c: [[5,1]] |
| d: [[2,4]] |
| e: [[1,3]] |
└──────────────────┘
"""
if not is_numpy_array_2d(data):
msg = "`from_numpy` only accepts 2D numpy arrays"
raise ValueError(msg)
if not _is_into_schema(schema):
msg = (
"`schema` is expected to be one of the following types: "
"IntoSchema | Sequence[str]. "
f"Got {type(schema)}."
)
raise TypeError(msg)
implementation = Implementation.from_backend(backend)
if is_eager_allowed(implementation):
ns = Version.MAIN.namespace.from_backend(implementation).compliant
return ns.from_numpy(data, schema).to_narwhals()
if implementation is Implementation.UNKNOWN: # pragma: no cover
_native_namespace = implementation.to_native_namespace()
try:
# implementation is UNKNOWN, Narwhals extension using this feature should
# implement `from_numpy` function in the top-level namespace.
native_frame: NativeDataFrame = _native_namespace.from_numpy(
data, schema=schema
)
except AttributeError as e:
msg = "Unknown namespace is expected to implement `from_numpy` function."
raise AttributeError(msg) from e
return from_native(native_frame, eager_only=True)
msg = (
f"{implementation} support in Narwhals is lazy-only, but `from_numpy` is an eager-only function.\n\n"
"Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n"
f" nw.from_numpy(arr, backend='pyarrow').lazy('{implementation}')"
)
raise ValueError(msg)
def _is_into_schema(obj: Any) -> TypeIs[_IntoSchema]:
from narwhals.schema import Schema
return (
obj is None or isinstance(obj, (Mapping, Schema)) or is_sequence_but_not_str(obj)
)
def from_arrow(
native_frame: IntoArrowTable, *, backend: IntoBackend[EagerAllowed]
) -> DataFrame[Any]: # pragma: no cover
"""Construct a DataFrame from an object which supports the PyCapsule Interface.
Arguments:
native_frame: Object which implements `__arrow_c_stream__`.
backend: specifies which eager backend instantiate to.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN` or `CUDF`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
Examples:
>>> import pandas as pd
>>> import polars as pl
>>> import narwhals as nw
>>>
>>> df_native = pd.DataFrame({"a": [1, 2], "b": [4.2, 5.1]})
>>> nw.from_arrow(df_native, backend="polars")
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| shape: (2, 2) |
| ┌─────┬─────┐ |
| │ a ┆ b │ |
| │ --- ┆ --- │ |
| │ i64 ┆ f64 │ |
| ╞═════╪═════╡ |
| │ 1 ┆ 4.2 │ |
| │ 2 ┆ 5.1 │ |
| └─────┴─────┘ |
└──────────────────┘
"""
if not (supports_arrow_c_stream(native_frame) or is_pyarrow_table(native_frame)):
msg = f"Given object of type {type(native_frame)} does not support PyCapsule interface"
raise TypeError(msg)
implementation = Implementation.from_backend(backend)
if is_eager_allowed(implementation):
ns = Version.MAIN.namespace.from_backend(implementation).compliant
return ns._dataframe.from_arrow(native_frame, context=ns).to_narwhals()
if implementation is Implementation.UNKNOWN: # pragma: no cover
_native_namespace = implementation.to_native_namespace()
try:
# implementation is UNKNOWN, Narwhals extension using this feature should
# implement PyCapsule support
native: NativeDataFrame = _native_namespace.DataFrame(native_frame)
except AttributeError as e:
msg = "Unknown namespace is expected to implement `DataFrame` class which accepts object which supports PyCapsule Interface."
raise AttributeError(msg) from e
return from_native(native, eager_only=True)
msg = (
f"{implementation} support in Narwhals is lazy-only, but `from_arrow` is an eager-only function.\n\n"
"Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n"
f" nw.from_arrow(df, backend='pyarrow').lazy('{implementation}')"
)
raise ValueError(msg)
def _get_sys_info() -> dict[str, str]:
"""System information.
Returns system and Python version information
Copied from sklearn
Returns:
Dictionary with system info.
"""
python = sys.version.replace("\n", " ")
blob = (
("python", python),
("executable", sys.executable),
("machine", platform.platform()),
)
return dict(blob)
def _get_deps_info() -> dict[str, str]:
"""Overview of the installed version of main dependencies.
This function does not import the modules to collect the version numbers
but instead relies on standard Python package metadata.
Returns version information on relevant Python libraries
This function and show_versions were copied from sklearn and adapted
Returns:
Mapping from dependency to version.
"""
from importlib.metadata import distributions
extra_names = ("narwhals", "numpy")
member_names = Implementation._member_names_
exclude = {"PYSPARK_CONNECT", "UNKNOWN"}
target_names = tuple(
name.lower() for name in (*extra_names, *member_names) if name not in exclude
)
result = dict.fromkeys(target_names, "") # Initialize with empty strings
for dist in distributions():
dist_name, dist_version = dist.name.lower(), dist.version
if dist_name in result: # exact match
result[dist_name] = dist_version
else: # prefix match
for target in target_names:
if not result[target] and dist_name.startswith(target):
result[target] = dist_version
break
return result
def show_versions() -> None:
"""Print useful debugging information.
Examples:
>>> from narwhals import show_versions
>>> show_versions() # doctest: +SKIP
"""
sys_info = _get_sys_info()
deps_info = _get_deps_info()
print("\nSystem:") # noqa: T201
for k, stat in sys_info.items():
print(f"{k:>10}: {stat}") # noqa: T201
print("\nPython dependencies:") # noqa: T201
for k, stat in deps_info.items():
print(f"{k:>13}: {stat}") # noqa: T201
def _validate_separators(
separator: str, native_separators: tuple[str, ...], **kwargs: Any
) -> None:
for native_separator in native_separators:
if native_separator in kwargs and kwargs[native_separator] != separator:
msg = (
f"`separator` and `{native_separator}` do not match: "
f"`separator`={separator} and `{native_separator}`={kwargs[native_separator]}."
)
raise TypeError(msg)
def _validate_separator_pyarrow(separator: str, **kwargs: Any) -> Any:
if "parse_options" in kwargs:
parse_options = kwargs.pop("parse_options")
if parse_options.delimiter != separator:
msg = (
"`separator` and `parse_options.delimiter` do not match: "
f"`separator`={separator} and `delimiter`={parse_options.delimiter}."
)
raise TypeError(msg)
return kwargs
from pyarrow import csv # ignore-banned-import
return {"parse_options": csv.ParseOptions(delimiter=separator)}
def read_csv(
source: FileSource,
*,
backend: IntoBackend[EagerAllowed],
separator: str = ",",
**kwargs: Any,
) -> DataFrame[Any]:
"""Read a CSV file into a DataFrame.
Arguments:
source: Path to a file.
backend: The eager backend for DataFrame creation.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN` or `CUDF`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
separator: Single byte character to use as separator in the file.
kwargs: Extra keyword arguments which are passed to the native CSV reader.
For example, you could use
`nw.read_csv('file.csv', backend='pandas', engine='pyarrow')`.
Examples:
>>> import narwhals as nw
>>> nw.read_csv("file.csv", backend="pandas") # doctest:+SKIP
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| a b |
| 0 1 4 |
| 1 2 5 |
└──────────────────┘
"""
impl = Implementation.from_backend(backend)
native_namespace = impl.to_native_namespace()
native_frame: NativeDataFrame
if impl in {Implementation.PANDAS, Implementation.MODIN, Implementation.CUDF}:
_validate_separators(separator, ("sep",), **kwargs)
native_frame = native_namespace.read_csv(
normalize_path(source), sep=separator, **kwargs
)
elif impl is Implementation.POLARS:
native_frame = native_namespace.read_csv(
normalize_path(source), separator=separator, **kwargs
)
elif impl is Implementation.PYARROW:
kwargs = _validate_separator_pyarrow(separator, **kwargs)
from pyarrow import csv # ignore-banned-import
native_frame = csv.read_csv(source, **kwargs)
elif impl in {
Implementation.PYSPARK,
Implementation.DASK,
Implementation.DUCKDB,
Implementation.IBIS,
Implementation.SQLFRAME,
Implementation.PYSPARK_CONNECT,
}:
msg = (
f"Expected eager backend, found {impl}.\n\n"
f"Hint: use nw.scan_csv(source={source}, backend={backend})"
)
raise ValueError(msg)
else: # pragma: no cover
try:
# implementation is UNKNOWN, Narwhals extension using this feature should
# implement `read_csv` function in the top-level namespace.
native_frame = native_namespace.read_csv(source=source, **kwargs)
except AttributeError as e:
msg = "Unknown namespace is expected to implement `read_csv` function."
raise AttributeError(msg) from e
return from_native(native_frame, eager_only=True)
def scan_csv(
source: FileSource,
*,
backend: IntoBackend[Backend],
separator: str = ",",
**kwargs: Any,
) -> LazyFrame[Any]:
"""Lazily read from a CSV file.
For the libraries that do not support lazy dataframes, the function reads
a csv file eagerly and then converts the resulting dataframe to a lazyframe.
Arguments:
source: Path to a file.
backend: The eager backend for DataFrame creation.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN` or `CUDF`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
separator: Single byte character to use as separator in the file.
kwargs: Extra keyword arguments which are passed to the native CSV reader.
For example, you could use
`nw.scan_csv('file.csv', backend=pd, engine='pyarrow')`.
Examples:
>>> import duckdb
>>> import narwhals as nw
>>>
>>> nw.scan_csv("file.csv", backend="duckdb").to_native() # doctest:+SKIP
┌─────────┬───────┐
│ a │ b │
│ varchar │ int32 │
├─────────┼───────┤
│ x │ 1 │
│ y │ 2 │
│ z │ 3 │
└─────────┴───────┘
"""
implementation = Implementation.from_backend(backend)
native_namespace = implementation.to_native_namespace()
native_frame: NativeDataFrame | NativeLazyFrame
source = normalize_path(source)
if implementation is Implementation.POLARS:
native_frame = native_namespace.scan_csv(source, separator=separator, **kwargs)
elif implementation in {
Implementation.PANDAS,
Implementation.MODIN,
Implementation.CUDF,
Implementation.DASK,
Implementation.IBIS,
}:
_validate_separators(separator, ("sep",), **kwargs)
native_frame = native_namespace.read_csv(source, sep=separator, **kwargs)
elif implementation is Implementation.DUCKDB:
_validate_separators(separator, ("delimiter", "delim", "sep"), **kwargs)
native_frame = native_namespace.read_csv(source, delimiter=separator, **kwargs)
elif implementation is Implementation.PYARROW:
kwargs = _validate_separator_pyarrow(separator, **kwargs)
from pyarrow import csv # ignore-banned-import
native_frame = csv.read_csv(source, **kwargs)
elif implementation.is_spark_like():
_validate_separators(separator, ("sep", "delimiter"), **kwargs)
if (session := kwargs.pop("session", None)) is None:
msg = "Spark like backends require a session object to be passed in `kwargs`."
raise ValueError(msg)
csv_reader = session.read.format("csv")
native_frame = (
csv_reader.load(source, sep=separator)
if (
implementation is Implementation.SQLFRAME
and implementation._backend_version() < (3, 27, 0)
)
else csv_reader.options(sep=separator, **kwargs).load(source)
)
else: # pragma: no cover
try:
# implementation is UNKNOWN, Narwhals extension using this feature should
# implement `scan_csv` function in the top-level namespace.
native_frame = native_namespace.scan_csv(source=source, **kwargs)
except AttributeError as e:
msg = "Unknown namespace is expected to implement `scan_csv` function."
raise AttributeError(msg) from e
return from_native(native_frame).lazy()
def read_parquet(
source: FileSource, *, backend: IntoBackend[EagerAllowed], **kwargs: Any
) -> DataFrame[Any]:
"""Read into a DataFrame from a parquet file.
Arguments:
source: Path to a file.
backend: The eager backend for DataFrame creation.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN` or `CUDF`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
kwargs: Extra keyword arguments which are passed to the native parquet reader.
For example, you could use
`nw.read_parquet('file.parquet', backend=pd, engine='pyarrow')`.
Examples:
>>> import pyarrow as pa
>>> import narwhals as nw
>>>
>>> nw.read_parquet("file.parquet", backend="pyarrow") # doctest:+SKIP
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
|pyarrow.Table |
|a: int64 |
|c: double |
|---- |
|a: [[1,2]] |
|c: [[0.2,0.1]] |
└──────────────────┘
"""
impl = Implementation.from_backend(backend)
native_namespace = impl.to_native_namespace()
native_frame: NativeDataFrame
if impl in {
Implementation.POLARS,
Implementation.PANDAS,
Implementation.MODIN,
Implementation.CUDF,
}:
source = normalize_path(source)
native_frame = native_namespace.read_parquet(source, **kwargs)
elif impl is Implementation.PYARROW:
import pyarrow.parquet as pq # ignore-banned-import
native_frame = pq.read_table(source, **kwargs) # type: ignore[arg-type]
elif impl in {
Implementation.PYSPARK,
Implementation.DASK,
Implementation.DUCKDB,
Implementation.IBIS,
Implementation.SQLFRAME,
Implementation.PYSPARK_CONNECT,
}:
msg = (
f"Expected eager backend, found {impl}.\n\n"
f"Hint: use nw.scan_parquet(source={source}, backend={backend})"
)
raise ValueError(msg)
else: # pragma: no cover
try:
# implementation is UNKNOWN, Narwhals extension using this feature should
# implement `read_parquet` function in the top-level namespace.
native_frame = native_namespace.read_parquet(source=source, **kwargs)
except AttributeError as e:
msg = "Unknown namespace is expected to implement `read_parquet` function."
raise AttributeError(msg) from e
return from_native(native_frame, eager_only=True)
def scan_parquet(
source: FileSource, *, backend: IntoBackend[Backend], **kwargs: Any
) -> LazyFrame[Any]:
"""Lazily read from a parquet file.
For the libraries that do not support lazy dataframes, the function reads
a parquet file eagerly and then converts the resulting dataframe to a lazyframe.
Note:
Spark like backends require a session object to be passed in `kwargs`.
For instance:
```py
import narwhals as nw
from sqlframe.duckdb import DuckDBSession
nw.scan_parquet(source, backend="sqlframe", session=DuckDBSession())
```
Arguments:
source: Path to a file.
backend: The eager backend for DataFrame creation.
`backend` can be specified in various ways
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
`POLARS`, `MODIN`, `CUDF`, `PYSPARK` or `SQLFRAME`.
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"`, `"cudf"`,
`"pyspark"` or `"sqlframe"`.
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin`, `cudf`,
`pyspark.sql` or `sqlframe`.
kwargs: Extra keyword arguments which are passed to the native parquet reader.
For example, you could use
`nw.scan_parquet('file.parquet', backend=pd, engine='pyarrow')`.
Examples:
>>> import dask.dataframe as dd
>>> from sqlframe.duckdb import DuckDBSession
>>> import narwhals as nw
>>>
>>> nw.scan_parquet("file.parquet", backend="dask").collect() # doctest:+SKIP
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| a b |
| 0 1 4 |
| 1 2 5 |
└──────────────────┘
>>> nw.scan_parquet(
... "file.parquet", backend="sqlframe", session=DuckDBSession()
... ).collect() # doctest:+SKIP
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| pyarrow.Table |
| a: int64 |
| b: int64 |
| ---- |
| a: [[1,2]] |
| b: [[4,5]] |
└──────────────────┘
"""
implementation = Implementation.from_backend(backend)
native_namespace = implementation.to_native_namespace()
native_frame: NativeDataFrame | NativeLazyFrame
source = normalize_path(source)
if implementation is Implementation.POLARS:
native_frame = native_namespace.scan_parquet(source, **kwargs)
elif implementation in {
Implementation.PANDAS,
Implementation.MODIN,
Implementation.CUDF,
Implementation.DASK,
Implementation.DUCKDB,
Implementation.IBIS,
}:
native_frame = native_namespace.read_parquet(source, **kwargs)
elif implementation is Implementation.PYARROW:
import pyarrow.parquet as pq # ignore-banned-import
native_frame = pq.read_table(source, **kwargs)
elif implementation.is_spark_like():
if (session := kwargs.pop("session", None)) is None:
msg = "Spark like backends require a session object to be passed in `kwargs`."
raise ValueError(msg)
pq_reader = session.read.format("parquet")
native_frame = (
pq_reader.load(source)
if (
implementation is Implementation.SQLFRAME
and implementation._backend_version() < (3, 27, 0)
)
else pq_reader.options(**kwargs).load(source)
)
else: # pragma: no cover
try:
# implementation is UNKNOWN, Narwhals extension using this feature should
# implement `scan_parquet` function in the top-level namespace.
native_frame = native_namespace.scan_parquet(source=source, **kwargs)
except AttributeError as e:
msg = "Unknown namespace is expected to implement `scan_parquet` function."
raise AttributeError(msg) from e
return from_native(native_frame).lazy()
def col(*names: str | Iterable[str]) -> Expr:
"""Creates an expression that references one or more columns by their name(s).
Arguments:
names: Name(s) of the columns to use.
Examples:
>>> import polars as pl
>>> import narwhals as nw
>>>
>>> df_native = pl.DataFrame({"a": [1, 2], "b": [3, 4], "c": ["x", "z"]})
>>> nw.from_native(df_native).select(nw.col("a", "b") * nw.col("b"))
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
| shape: (2, 2) |
| ┌─────┬─────┐ |
| │ a ┆ b │ |
| │ --- ┆ --- │ |
| │ i64 ┆ i64 │ |
| ╞═════╪═════╡ |
| │ 3 ┆ 9 │ |
| │ 8 ┆ 16 │ |