@@ -44,41 +44,40 @@ There are three steps to writing dataframe-agnostic code using Narwhals:
44
44
Here's an example of a dataframe agnostic function:
45
45
46
46
``` python
47
- from typing import TypeVar
47
+ from typing import Any
48
48
import pandas as pd
49
49
import polars as pl
50
50
51
- from narwhals import translate_frame, get_namespace, to_native
52
-
53
- AnyDataFrame = TypeVar(" AnyDataFrame" )
51
+ import narwhals as nw
54
52
55
53
56
54
def my_agnostic_function (
57
- suppliers_native : AnyDataFrame,
58
- parts_native : AnyDataFrame,
59
- ) -> AnyDataFrame:
60
- suppliers = translate_frame(suppliers_native)
61
- parts = translate_frame(parts_native)
62
- pl = get_namespace(suppliers)
55
+ suppliers_native ,
56
+ parts_native ,
57
+ ):
58
+ suppliers = nw.DataFrame(suppliers_native)
59
+ parts = nw.DataFrame(parts_native)
63
60
64
61
result = (
65
62
suppliers.join(parts, left_on = " city" , right_on = " city" )
66
63
.filter(
67
- pl .col(" color" ).is_in([" Red" , " Green" ]),
68
- pl .col(" weight" ) > 14 ,
64
+ nw .col(" color" ).is_in([" Red" , " Green" ]),
65
+ nw .col(" weight" ) > 14 ,
69
66
)
70
67
.group_by(" s" , " p" )
71
68
.agg(
72
- weight_mean = pl .col(" weight" ).mean(),
73
- weight_max = pl .col(" weight" ).max(),
69
+ weight_mean = nw .col(" weight" ).mean(),
70
+ weight_max = nw .col(" weight" ).max(),
74
71
)
75
- )
76
- return to_native(result)
72
+ ).with_columns(nw.col(" weight_max" ).cast(nw.Int64))
73
+ return nw.to_native(result)
74
+
77
75
```
78
76
You can pass in a pandas or Polars dataframe, the output will be the same!
79
77
Let's try it out:
80
78
81
79
``` python
80
+
82
81
suppliers = {
83
82
" s" : [" S1" , " S2" , " S3" , " S4" , " S5" ],
84
83
" sname" : [" Smith" , " Jones" , " Blake" , " Clark" , " Adams" ],
0 commit comments