Reset repository and upload final project (part 9)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +3 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._INSTALLER +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._METADATA +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._RECORD +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._WHEEL +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._licenses +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/INSTALLER +1 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/METADATA +349 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/RECORD +330 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/WHEEL +4 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/licenses/._LICENSE.md +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/licenses/LICENSE.md +21 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/dataframe.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/dependencies.py +631 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/dtypes.py +1042 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/exceptions.py +114 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/expr.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/expr_cat.py +41 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/expr_dt.py +738 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/expr_list.py +300 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/expr_name.py +131 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/expr_str.py +579 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/expr_struct.py +47 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/functions.py +1829 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/group_by.py +170 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/plugins.py +120 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/py.typed +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/schema.py +365 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/selectors.py +322 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/series.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/series_cat.py +27 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/series_dt.py +647 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/series_list.py +247 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/series_str.py +519 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/series_struct.py +30 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/sql.py +105 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/.___init__.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/.___pycache__ +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/._v1 +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/._v2 +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/__init__.py +5 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/.___init__.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/.___pycache__ +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/.__dtypes.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/.__namespace.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/._dependencies.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/._dtypes.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/._selectors.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/._typing.py +0 -0
- .venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/__init__.py +1156 -0
.gitattributes
CHANGED
|
@@ -68,3 +68,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 68 |
.venv_haddock/lib/python3.12/site-packages/haddock/prodrg/prodrg_aarch64-linux filter=lfs diff=lfs merge=lfs -text
|
| 69 |
.venv_haddock/lib/python3.12/site-packages/haddock/prodrg/prodrg_arm64-darwin filter=lfs diff=lfs merge=lfs -text
|
| 70 |
.venv_haddock/lib/python3.12/site-packages/haddock/prodrg/prodrg_x86_64-linux filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
.venv_haddock/lib/python3.12/site-packages/haddock/prodrg/prodrg_aarch64-linux filter=lfs diff=lfs merge=lfs -text
|
| 69 |
.venv_haddock/lib/python3.12/site-packages/haddock/prodrg/prodrg_arm64-darwin filter=lfs diff=lfs merge=lfs -text
|
| 70 |
.venv_haddock/lib/python3.12/site-packages/haddock/prodrg/prodrg_x86_64-linux filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
.venv_haddock/lib/python3.12/site-packages/numpy/_core/_multiarray_tests.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
.venv_haddock/lib/python3.12/site-packages/numpy/_core/_multiarray_umath.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
.venv_haddock/lib/python3.12/site-packages/numpy/_core/_simd.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._INSTALLER
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._METADATA
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._RECORD
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._WHEEL
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/._licenses
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: narwhals
|
| 3 |
+
Version: 2.19.0
|
| 4 |
+
Summary: Extremely lightweight compatibility layer between dataframe libraries
|
| 5 |
+
Project-URL: Homepage, https://github.com/narwhals-dev/narwhals
|
| 6 |
+
Project-URL: Documentation, https://narwhals-dev.github.io/narwhals/
|
| 7 |
+
Project-URL: Repository, https://github.com/narwhals-dev/narwhals
|
| 8 |
+
Project-URL: Bug Tracker, https://github.com/narwhals-dev/narwhals/issues
|
| 9 |
+
Author-email: Marco Gorelli <hello_narwhals@proton.me>
|
| 10 |
+
License: MIT License
|
| 11 |
+
|
| 12 |
+
Copyright (c) 2024 to present, Marco Gorelli
|
| 13 |
+
|
| 14 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 15 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 16 |
+
in the Software without restriction, including without limitation the rights
|
| 17 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 18 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 19 |
+
furnished to do so, subject to the following conditions:
|
| 20 |
+
|
| 21 |
+
The above copyright notice and this permission notice shall be included in all
|
| 22 |
+
copies or substantial portions of the Software.
|
| 23 |
+
|
| 24 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 25 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 26 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 27 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 28 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 29 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 30 |
+
SOFTWARE.
|
| 31 |
+
License-File: LICENSE.md
|
| 32 |
+
Keywords: cudf,dask,dataframes,interoperability,modin,pandas,polars,pyarrow
|
| 33 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 34 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 35 |
+
Classifier: Operating System :: OS Independent
|
| 36 |
+
Classifier: Programming Language :: Python :: 3
|
| 37 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 38 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 39 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 40 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 41 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 42 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 43 |
+
Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
|
| 44 |
+
Classifier: Typing :: Typed
|
| 45 |
+
Requires-Python: >=3.9
|
| 46 |
+
Provides-Extra: cudf
|
| 47 |
+
Requires-Dist: cudf-cu12>=24.10.0; extra == 'cudf'
|
| 48 |
+
Provides-Extra: dask
|
| 49 |
+
Requires-Dist: dask[dataframe]>=2024.8; extra == 'dask'
|
| 50 |
+
Provides-Extra: duckdb
|
| 51 |
+
Requires-Dist: duckdb>=1.1; extra == 'duckdb'
|
| 52 |
+
Provides-Extra: ibis
|
| 53 |
+
Requires-Dist: ibis-framework>=6.0.0; extra == 'ibis'
|
| 54 |
+
Requires-Dist: packaging; extra == 'ibis'
|
| 55 |
+
Requires-Dist: pyarrow-hotfix; extra == 'ibis'
|
| 56 |
+
Requires-Dist: rich; extra == 'ibis'
|
| 57 |
+
Provides-Extra: modin
|
| 58 |
+
Requires-Dist: modin; extra == 'modin'
|
| 59 |
+
Provides-Extra: pandas
|
| 60 |
+
Requires-Dist: pandas>=1.1.3; extra == 'pandas'
|
| 61 |
+
Provides-Extra: polars
|
| 62 |
+
Requires-Dist: polars>=0.20.4; extra == 'polars'
|
| 63 |
+
Provides-Extra: pyarrow
|
| 64 |
+
Requires-Dist: pyarrow>=13.0.0; extra == 'pyarrow'
|
| 65 |
+
Provides-Extra: pyspark
|
| 66 |
+
Requires-Dist: pyspark>=3.5.0; extra == 'pyspark'
|
| 67 |
+
Provides-Extra: pyspark-connect
|
| 68 |
+
Requires-Dist: pyspark[connect]>=3.5.0; extra == 'pyspark-connect'
|
| 69 |
+
Provides-Extra: sql
|
| 70 |
+
Requires-Dist: duckdb>=1.1; extra == 'sql'
|
| 71 |
+
Requires-Dist: sqlparse; extra == 'sql'
|
| 72 |
+
Provides-Extra: sqlframe
|
| 73 |
+
Requires-Dist: sqlframe!=3.39.3,>=3.22.0; extra == 'sqlframe'
|
| 74 |
+
Description-Content-Type: text/markdown
|
| 75 |
+
|
| 76 |
+
# Narwhals
|
| 77 |
+
|
| 78 |
+
<h1 align="center">
|
| 79 |
+
<img
|
| 80 |
+
width="400"
|
| 81 |
+
alt="narwhals_small"
|
| 82 |
+
src="https://github.com/user-attachments/assets/968545af-ea0f-48bb-8377-144e93f7abf8">
|
| 83 |
+
</h1>
|
| 84 |
+
|
| 85 |
+
[](https://badge.fury.io/py/narwhals)
|
| 86 |
+
[](https://pepy.tech/project/narwhals)
|
| 87 |
+
[](https://peps.python.org/pep-0740/)
|
| 88 |
+
[](https://pypi.org/project/narwhals)
|
| 89 |
+
|
| 90 |
+
Extremely lightweight and extensible compatibility layer between dataframe libraries!
|
| 91 |
+
|
| 92 |
+
- **Full API support**: cuDF, Modin, pandas, Polars, PyArrow.
|
| 93 |
+
- **Lazy-only support**: Daft, Dask, DuckDB, Ibis, PySpark, SQLFrame.
|
| 94 |
+
|
| 95 |
+
Seamlessly support all, without depending on any!
|
| 96 |
+
|
| 97 |
+
- ✅ **Just use** [a subset of **the Polars API**](https://narwhals-dev.github.io/narwhals/api-reference/), no need to learn anything new
|
| 98 |
+
- ✅ **Zero dependencies**, Narwhals only uses what
|
| 99 |
+
the user passes in so your library can stay lightweight
|
| 100 |
+
- ✅ Separate **lazy** and eager APIs, use **expressions**
|
| 101 |
+
- ✅ Support pandas' complicated type system and index, without
|
| 102 |
+
either getting in the way
|
| 103 |
+
- ✅ **100% branch coverage**, tested against pandas and Polars nightly builds
|
| 104 |
+
- ✅ **Negligible overhead**, see [overhead](https://narwhals-dev.github.io/narwhals/overhead/)
|
| 105 |
+
- ✅ Let your IDE help you thanks to **full static typing**, see [typing](https://narwhals-dev.github.io/narwhals/api-reference/typing/)
|
| 106 |
+
- ✅ **Perfect backwards compatibility policy**,
|
| 107 |
+
see [stable api](https://narwhals-dev.github.io/narwhals/backcompat/) for how to opt-in
|
| 108 |
+
|
| 109 |
+
Get started!
|
| 110 |
+
|
| 111 |
+
- [Read the documentation](https://narwhals-dev.github.io/narwhals/)
|
| 112 |
+
- [Chat with us on Discord!](https://discord.gg/V3PqtB4VA4)
|
| 113 |
+
- [Join our community call](https://calendar.google.com/calendar/embed?src=27ff6dc5f598c1d94c1f6e627a1aaae680e2fac88f848bda1f2c7946ae74d5ab%40group.calendar.google.com)
|
| 114 |
+
- [Read the contributing guide](https://github.com/narwhals-dev/narwhals/blob/main/CONTRIBUTING.md)
|
| 115 |
+
|
| 116 |
+
<details>
|
| 117 |
+
<summary>Table of contents</summary>
|
| 118 |
+
|
| 119 |
+
- [Narwhals](#narwhals)
|
| 120 |
+
- [Installation](#installation)
|
| 121 |
+
- [Usage](#usage)
|
| 122 |
+
- [Example](#example)
|
| 123 |
+
- [Scope](#scope)
|
| 124 |
+
- [Roadmap](#roadmap)
|
| 125 |
+
- [Used by](#used-by)
|
| 126 |
+
- [Sponsors and institutional partners](#sponsors-and-institutional-partners)
|
| 127 |
+
- [Support](#support)
|
| 128 |
+
- [Appears on](#appears-on)
|
| 129 |
+
- [Why "Narwhals"?](#why-narwhals)
|
| 130 |
+
|
| 131 |
+
</details>
|
| 132 |
+
|
| 133 |
+
## Installation
|
| 134 |
+
|
| 135 |
+
- pip (recommended, as it's the most up-to-date)
|
| 136 |
+
```
|
| 137 |
+
pip install narwhals
|
| 138 |
+
```
|
| 139 |
+
- conda-forge (also fine, but the latest version may take longer to appear)
|
| 140 |
+
```
|
| 141 |
+
conda install -c conda-forge narwhals
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
## Usage
|
| 145 |
+
|
| 146 |
+
There are three steps to writing dataframe-agnostic code using Narwhals:
|
| 147 |
+
|
| 148 |
+
1. use `narwhals.from_native` to wrap a pandas/Polars/Modin/cuDF/PyArrow
|
| 149 |
+
DataFrame/LazyFrame in a Narwhals class
|
| 150 |
+
2. use the [subset of the Polars API supported by Narwhals](https://narwhals-dev.github.io/narwhals/api-reference/)
|
| 151 |
+
3. use `narwhals.to_native` to return an object to the user in its original
|
| 152 |
+
dataframe flavour. For example:
|
| 153 |
+
|
| 154 |
+
- if you started with pandas, you'll get pandas back
|
| 155 |
+
- if you started with Polars, you'll get Polars back
|
| 156 |
+
- if you started with Modin, you'll get Modin back (and compute will be distributed)
|
| 157 |
+
- if you started with cuDF, you'll get cuDF back (and compute will happen on GPU)
|
| 158 |
+
- if you started with PyArrow, you'll get PyArrow back
|
| 159 |
+
|
| 160 |
+
<h1 align="left">
|
| 161 |
+
<img
|
| 162 |
+
width="600"
|
| 163 |
+
alt="narwhals_gif"
|
| 164 |
+
src="https://github.com/user-attachments/assets/88292d3c-6359-4155-973d-d0f8e3fbf5ac">
|
| 165 |
+
|
| 166 |
+
</h1>
|
| 167 |
+
|
| 168 |
+
## Example
|
| 169 |
+
|
| 170 |
+
Narwhals allows you to define dataframe-agnostic functions. For example:
|
| 171 |
+
|
| 172 |
+
```python
|
| 173 |
+
import narwhals as nw
|
| 174 |
+
from narwhals.typing import IntoFrameT
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def agnostic_function(
|
| 178 |
+
df_native: IntoFrameT,
|
| 179 |
+
date_column: str,
|
| 180 |
+
price_column: str,
|
| 181 |
+
) -> IntoFrameT:
|
| 182 |
+
return (
|
| 183 |
+
nw.from_native(df_native)
|
| 184 |
+
.group_by(nw.col(date_column).dt.truncate("1mo"))
|
| 185 |
+
.agg(nw.col(price_column).mean())
|
| 186 |
+
.sort(date_column)
|
| 187 |
+
.to_native()
|
| 188 |
+
)
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
You can then pass `pandas.DataFrame`, `polars.DataFrame`, `polars.LazyFrame`, `duckdb.DuckDBPyRelation`,
|
| 192 |
+
`pyspark.sql.DataFrame`, `pyarrow.Table`, and more, to `agnostic_function`. In each case, no additional
|
| 193 |
+
dependencies will be required, and computation will stay native to the input library:
|
| 194 |
+
|
| 195 |
+
```python
|
| 196 |
+
import pandas as pd
|
| 197 |
+
import polars as pl
|
| 198 |
+
from datetime import datetime
|
| 199 |
+
|
| 200 |
+
data = {
|
| 201 |
+
"date": [datetime(2020, 1, 1), datetime(2020, 1, 8), datetime(2020, 2, 3)],
|
| 202 |
+
"price": [1, 4, 3],
|
| 203 |
+
}
|
| 204 |
+
print("pandas result:")
|
| 205 |
+
print(agnostic_function(pd.DataFrame(data), "date", "price"))
|
| 206 |
+
print()
|
| 207 |
+
print("Polars result:")
|
| 208 |
+
print(agnostic_function(pl.DataFrame(data), "date", "price"))
|
| 209 |
+
```
|
| 210 |
+
|
| 211 |
+
```terminal
|
| 212 |
+
pandas result:
|
| 213 |
+
date price
|
| 214 |
+
0 2020-01-01 2.5
|
| 215 |
+
1 2020-02-01 3.0
|
| 216 |
+
|
| 217 |
+
Polars result:
|
| 218 |
+
shape: (2, 2)
|
| 219 |
+
┌─────────────────────┬───────┐
|
| 220 |
+
│ date ┆ price │
|
| 221 |
+
│ --- ┆ --- │
|
| 222 |
+
│ datetime[μs] ┆ f64 │
|
| 223 |
+
╞═════════════════════╪═══════╡
|
| 224 |
+
│ 2020-01-01 00:00:00 ┆ 2.5 │
|
| 225 |
+
│ 2020-02-01 00:00:00 ┆ 3.0 │
|
| 226 |
+
└─────────────────────┴───────┘
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
See the [tutorial](https://narwhals-dev.github.io/narwhals/basics/dataframe/) for several examples!
|
| 230 |
+
|
| 231 |
+
## Scope
|
| 232 |
+
|
| 233 |
+
- Do you maintain a dataframe-consuming library?
|
| 234 |
+
- Do you have a specific Polars function in mind that you would like Narwhals to have in order to make your work easier?
|
| 235 |
+
|
| 236 |
+
If you said yes to both, we'd love to hear from you!
|
| 237 |
+
|
| 238 |
+
## Roadmap
|
| 239 |
+
|
| 240 |
+
See [roadmap discussion on GitHub](https://github.com/narwhals-dev/narwhals/discussions/1370)
|
| 241 |
+
for an up-to-date plan of future work.
|
| 242 |
+
|
| 243 |
+
## Used by
|
| 244 |
+
|
| 245 |
+
Join the party!
|
| 246 |
+
|
| 247 |
+
- [altair](https://github.com/vega/altair/)
|
| 248 |
+
- [bokeh](https://github.com/bokeh/bokeh)
|
| 249 |
+
- [darts](https://github.com/unit8co/darts)
|
| 250 |
+
- [fairlearn](https://github.com/fairlearn/fairlearn)
|
| 251 |
+
- [formulaic](https://github.com/matthewwardrop/formulaic)
|
| 252 |
+
- [gt-extras](https://github.com/posit-dev/gt-extras)
|
| 253 |
+
- [hierarchicalforecast](https://github.com/Nixtla/hierarchicalforecast)
|
| 254 |
+
- [marimo](https://github.com/marimo-team/marimo)
|
| 255 |
+
- [metalearners](https://github.com/Quantco/metalearners)
|
| 256 |
+
- [mosaic](https://github.com/uwdata/mosaic)
|
| 257 |
+
- [panel-graphic-walker](https://github.com/panel-extensions/panel-graphic-walker)
|
| 258 |
+
- [plotly](https://plotly.com)
|
| 259 |
+
- [pointblank](https://github.com/posit-dev/pointblank)
|
| 260 |
+
- [pymarginaleffects](https://github.com/vincentarelbundock/pymarginaleffects)
|
| 261 |
+
- [pyreadstat](https://github.com/Roche/pyreadstat)
|
| 262 |
+
- [py-shiny](https://github.com/posit-dev/py-shiny)
|
| 263 |
+
- [rio](https://github.com/rio-labs/rio)
|
| 264 |
+
- [scikit-lego](https://github.com/koaning/scikit-lego)
|
| 265 |
+
- [scikit-playtime](https://github.com/koaning/scikit-playtime)
|
| 266 |
+
- [tabmat](https://github.com/Quantco/tabmat)
|
| 267 |
+
- [tea-tasting](https://github.com/e10v/tea-tasting)
|
| 268 |
+
- [timebasedcv](https://github.com/FBruzzesi/timebasedcv)
|
| 269 |
+
- [tubular](https://github.com/lvgig/tubular)
|
| 270 |
+
- [Validoopsie](https://github.com/akmalsoliev/Validoopsie)
|
| 271 |
+
- [vegafusion](https://github.com/vega/vegafusion)
|
| 272 |
+
- [wimsey](https://github.com/benrutter/wimsey)
|
| 273 |
+
|
| 274 |
+
Feel free to add your project to the list if it's missing, and/or
|
| 275 |
+
[chat with us on Discord](https://discord.gg/V3PqtB4VA4) if you'd like any support.
|
| 276 |
+
|
| 277 |
+
## Sponsors and institutional partners
|
| 278 |
+
|
| 279 |
+
Narwhals is 100% independent, community-driven, and community-owned.
|
| 280 |
+
We are extremely grateful to the following organisations for having
|
| 281 |
+
provided some funding / development time:
|
| 282 |
+
|
| 283 |
+
- [Quansight Labs](https://labs.quansight.org)
|
| 284 |
+
- [Quansight Futures](https://www.qi.ventures)
|
| 285 |
+
- [OpenTeams](https://www.openteams.com)
|
| 286 |
+
- [POSSEE initiative](https://possee.org)
|
| 287 |
+
- [BYU-Idaho](https://www.byui.edu)
|
| 288 |
+
|
| 289 |
+
If you contribute to Narwhals on your organization's time, please let us know. We'd be happy to add your employer
|
| 290 |
+
to this list!
|
| 291 |
+
|
| 292 |
+
## Support
|
| 293 |
+
|
| 294 |
+
If you'd like to say "thank you", please give us a ⭐ star ⭐.
|
| 295 |
+
|
| 296 |
+
Please contact [hello_narwhals@proton.me](hello_narwhals@proton.me) if you would like to:
|
| 297 |
+
|
| 298 |
+
- Receive professional support (e.g., if you're using or would like to use Narwhals at your company).
|
| 299 |
+
- Have any Narwhals fixes / features prioritised.
|
| 300 |
+
- Commission any Narwhals plugins for new backends.
|
| 301 |
+
|
| 302 |
+
## Appears on
|
| 303 |
+
|
| 304 |
+
Narwhals has been featured in several talks, podcasts, and blog posts:
|
| 305 |
+
|
| 306 |
+
- [Inspiring Computing Podcast](https://www.inspiringcomputing.com/2107763/episodes/16702460-the-rise-of-narwhals-in-open-source)
|
| 307 |
+
The Rise of Narwhals in Open-Source
|
| 308 |
+
|
| 309 |
+
- [PyCon DE & PyData 2025](https://youtu.be/DJk782DWcss)
|
| 310 |
+
How Narwhals is silently bringing pandas, Polars, DuckDB, PyArrow, and more together
|
| 311 |
+
|
| 312 |
+
- [The Python Exchange March 2025](https://youtu.be/TvFWFlK-2po)
|
| 313 |
+
What Can Narwhals Do for You?
|
| 314 |
+
|
| 315 |
+
- [PyData London 2025](https://youtu.be/r2PxJlO7_QA)
|
| 316 |
+
How Narwhals brings Polars, DuckDB, PyArrow, & pandas together
|
| 317 |
+
|
| 318 |
+
- [Talk Python to me Podcast](https://youtu.be/FSH7BZ0tuE0)
|
| 319 |
+
Ahoy, Narwhals are bridging the data science APIs
|
| 320 |
+
|
| 321 |
+
- [Python Bytes Podcast](https://www.youtube.com/live/N7w_ESVW40I?si=y-wN1uCsAuJOKlOT&t=382)
|
| 322 |
+
Episode 402, topic #2
|
| 323 |
+
|
| 324 |
+
- [Super Data Science: ML & AI Podcast](https://www.youtube.com/watch?v=TeG4U8R0U8U)
|
| 325 |
+
Narwhals: For Pandas-to-Polars DataFrame Compatibility
|
| 326 |
+
|
| 327 |
+
- [Sample Space Podcast | probabl](https://youtu.be/8hYdq4sWbbQ?si=WG0QP1CZ6gkFf18b)
|
| 328 |
+
How Narwhals has many end users ... that never use it directly. - Marco Gorelli
|
| 329 |
+
|
| 330 |
+
- [The Real Python Podcast](https://www.youtube.com/watch?v=w5DFZbFYzCM)
|
| 331 |
+
Narwhals: Expanding DataFrame Compatibility Between Libraries
|
| 332 |
+
|
| 333 |
+
- [Pycon Lithuania 2024](https://www.youtube.com/watch?v=-mdx7Cn6_6E)
|
| 334 |
+
Marco Gorelli - DataFrame interoperatiblity - what's been achieved, and what comes next?
|
| 335 |
+
|
| 336 |
+
- [Pycon Italy 2024](https://www.youtube.com/watch?v=3IqUli9XsmQ)
|
| 337 |
+
How you can write a dataframe-agnostic library - Marco Gorelli
|
| 338 |
+
|
| 339 |
+
- [Polars Blog Post](https://pola.rs/posts/lightweight_plotting/)
|
| 340 |
+
Polars has a new lightweight plotting backend
|
| 341 |
+
|
| 342 |
+
- [Quansight Labs blog post (w/ Scikit-Lego)](https://labs.quansight.org/blog/scikit-lego-narwhals)
|
| 343 |
+
How Narwhals and scikit-lego came together to achieve dataframe-agnosticism
|
| 344 |
+
|
| 345 |
+
## Why "Narwhals"?
|
| 346 |
+
|
| 347 |
+
[Coz they are so awesome](https://youtu.be/ykwqXuMPsoc?si=A-i8LdR38teYsos4).
|
| 348 |
+
|
| 349 |
+
Thanks to [Olha Urdeichuk](https://www.fiverr.com/olhaurdeichuk) for the illustration!
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
| 5 |
+
narwhals-2.19.0.dist-info/licenses/LICENSE.md,sha256=gRRF8wFHuPDJ1ETJAl_VKPlTLFS3uD9uI2hHPckc_fA,1082
|
| 6 |
+
narwhals/__init__.py,sha256=2K-Vi5Dtx6Sc6-EwIlMGKYg50WiP8AXB2GWB-v_AUa4,3339
|
| 7 |
+
narwhals/__pycache__/__init__.cpython-312.pyc,,
|
| 8 |
+
narwhals/__pycache__/_constants.cpython-312.pyc,,
|
| 9 |
+
narwhals/__pycache__/_duration.cpython-312.pyc,,
|
| 10 |
+
narwhals/__pycache__/_enum.cpython-312.pyc,,
|
| 11 |
+
narwhals/__pycache__/_exceptions.cpython-312.pyc,,
|
| 12 |
+
narwhals/__pycache__/_expression_parsing.cpython-312.pyc,,
|
| 13 |
+
narwhals/__pycache__/_namespace.cpython-312.pyc,,
|
| 14 |
+
narwhals/__pycache__/_native.cpython-312.pyc,,
|
| 15 |
+
narwhals/__pycache__/_translate.cpython-312.pyc,,
|
| 16 |
+
narwhals/__pycache__/_typing.cpython-312.pyc,,
|
| 17 |
+
narwhals/__pycache__/_typing_compat.cpython-312.pyc,,
|
| 18 |
+
narwhals/__pycache__/_utils.cpython-312.pyc,,
|
| 19 |
+
narwhals/__pycache__/compliant.cpython-312.pyc,,
|
| 20 |
+
narwhals/__pycache__/dataframe.cpython-312.pyc,,
|
| 21 |
+
narwhals/__pycache__/dependencies.cpython-312.pyc,,
|
| 22 |
+
narwhals/__pycache__/dtypes.cpython-312.pyc,,
|
| 23 |
+
narwhals/__pycache__/exceptions.cpython-312.pyc,,
|
| 24 |
+
narwhals/__pycache__/expr.cpython-312.pyc,,
|
| 25 |
+
narwhals/__pycache__/expr_cat.cpython-312.pyc,,
|
| 26 |
+
narwhals/__pycache__/expr_dt.cpython-312.pyc,,
|
| 27 |
+
narwhals/__pycache__/expr_list.cpython-312.pyc,,
|
| 28 |
+
narwhals/__pycache__/expr_name.cpython-312.pyc,,
|
| 29 |
+
narwhals/__pycache__/expr_str.cpython-312.pyc,,
|
| 30 |
+
narwhals/__pycache__/expr_struct.cpython-312.pyc,,
|
| 31 |
+
narwhals/__pycache__/functions.cpython-312.pyc,,
|
| 32 |
+
narwhals/__pycache__/group_by.cpython-312.pyc,,
|
| 33 |
+
narwhals/__pycache__/plugins.cpython-312.pyc,,
|
| 34 |
+
narwhals/__pycache__/schema.cpython-312.pyc,,
|
| 35 |
+
narwhals/__pycache__/selectors.cpython-312.pyc,,
|
| 36 |
+
narwhals/__pycache__/series.cpython-312.pyc,,
|
| 37 |
+
narwhals/__pycache__/series_cat.cpython-312.pyc,,
|
| 38 |
+
narwhals/__pycache__/series_dt.cpython-312.pyc,,
|
| 39 |
+
narwhals/__pycache__/series_list.cpython-312.pyc,,
|
| 40 |
+
narwhals/__pycache__/series_str.cpython-312.pyc,,
|
| 41 |
+
narwhals/__pycache__/series_struct.cpython-312.pyc,,
|
| 42 |
+
narwhals/__pycache__/sql.cpython-312.pyc,,
|
| 43 |
+
narwhals/__pycache__/this.cpython-312.pyc,,
|
| 44 |
+
narwhals/__pycache__/translate.cpython-312.pyc,,
|
| 45 |
+
narwhals/__pycache__/typing.cpython-312.pyc,,
|
| 46 |
+
narwhals/__pycache__/utils.cpython-312.pyc,,
|
| 47 |
+
narwhals/_arrow/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 48 |
+
narwhals/_arrow/__pycache__/__init__.cpython-312.pyc,,
|
| 49 |
+
narwhals/_arrow/__pycache__/dataframe.cpython-312.pyc,,
|
| 50 |
+
narwhals/_arrow/__pycache__/expr.cpython-312.pyc,,
|
| 51 |
+
narwhals/_arrow/__pycache__/group_by.cpython-312.pyc,,
|
| 52 |
+
narwhals/_arrow/__pycache__/namespace.cpython-312.pyc,,
|
| 53 |
+
narwhals/_arrow/__pycache__/selectors.cpython-312.pyc,,
|
| 54 |
+
narwhals/_arrow/__pycache__/series.cpython-312.pyc,,
|
| 55 |
+
narwhals/_arrow/__pycache__/series_cat.cpython-312.pyc,,
|
| 56 |
+
narwhals/_arrow/__pycache__/series_dt.cpython-312.pyc,,
|
| 57 |
+
narwhals/_arrow/__pycache__/series_list.cpython-312.pyc,,
|
| 58 |
+
narwhals/_arrow/__pycache__/series_str.cpython-312.pyc,,
|
| 59 |
+
narwhals/_arrow/__pycache__/series_struct.cpython-312.pyc,,
|
| 60 |
+
narwhals/_arrow/__pycache__/typing.cpython-312.pyc,,
|
| 61 |
+
narwhals/_arrow/__pycache__/utils.cpython-312.pyc,,
|
| 62 |
+
narwhals/_arrow/dataframe.py,sha256=SIlHQrE80jg19Vq33Y2pCwNzhWDJj-0k-VD3zkzBYCw,31067
|
| 63 |
+
narwhals/_arrow/expr.py,sha256=T0F5hG0k4jeITT__B6UIHVGvkgGK1uXpZTyu8ZuzPyg,9433
|
| 64 |
+
narwhals/_arrow/group_by.py,sha256=3kNOSdauoXDWtMMAhOQfrQtbmhC1bzSN7Sl56QfwQE4,9174
|
| 65 |
+
narwhals/_arrow/namespace.py,sha256=gpxdqsMjeKUTw93dabbCPRlmZJ_w8LvwEG5VQYK7xYo,11272
|
| 66 |
+
narwhals/_arrow/selectors.py,sha256=kShb4WWC9UKQO_MTrYoLNKyo2KLdofjFRh1KBRtXCKQ,882
|
| 67 |
+
narwhals/_arrow/series.py,sha256=ZdmyaElQif1QOUKvMdeyGpswgzndXMDkz-Toq_8yL2c,45518
|
| 68 |
+
narwhals/_arrow/series_cat.py,sha256=j2DFbFEoaW2vSnLnCycspYNtbNYeWvVSeLELYb_3zF0,686
|
| 69 |
+
narwhals/_arrow/series_dt.py,sha256=xTQt39PKTVPkeVwh87soCld_ll6-v_OQJTdUKJBBjS4,9026
|
| 70 |
+
narwhals/_arrow/series_list.py,sha256=EDwxUa5bm5jrYci8SIK9sXa8gMv8k7GnCUndixg55gs,1461
|
| 71 |
+
narwhals/_arrow/series_str.py,sha256=n87Jqa7q-O-GonBiwWy3V7itGrDYB168Jk9Z-yj7_ns,5179
|
| 72 |
+
narwhals/_arrow/series_struct.py,sha256=MorW6vTLKxqpR96NhB5RxkkBWOxrCTyvJ76Ilnwb7LY,504
|
| 73 |
+
narwhals/_arrow/typing.py,sha256=W3Vz_kc5zw94VeYzrC9xNPYpJBZ3DOSyfpuWPUVEW1M,2359
|
| 74 |
+
narwhals/_arrow/utils.py,sha256=9ntQC59VAxpuZDsd2C6NNc510dNWle1VxEMKoLSEOjs,21010
|
| 75 |
+
narwhals/_compliant/__init__.py,sha256=Xzk2TdU1KItMCg-r_cs599PPF8x9BMjgSMiOalW9Vjs,2319
|
| 76 |
+
narwhals/_compliant/__pycache__/__init__.cpython-312.pyc,,
|
| 77 |
+
narwhals/_compliant/__pycache__/any_namespace.cpython-312.pyc,,
|
| 78 |
+
narwhals/_compliant/__pycache__/column.cpython-312.pyc,,
|
| 79 |
+
narwhals/_compliant/__pycache__/dataframe.cpython-312.pyc,,
|
| 80 |
+
narwhals/_compliant/__pycache__/expr.cpython-312.pyc,,
|
| 81 |
+
narwhals/_compliant/__pycache__/group_by.cpython-312.pyc,,
|
| 82 |
+
narwhals/_compliant/__pycache__/namespace.cpython-312.pyc,,
|
| 83 |
+
narwhals/_compliant/__pycache__/selectors.cpython-312.pyc,,
|
| 84 |
+
narwhals/_compliant/__pycache__/series.cpython-312.pyc,,
|
| 85 |
+
narwhals/_compliant/__pycache__/typing.cpython-312.pyc,,
|
| 86 |
+
narwhals/_compliant/__pycache__/window.cpython-312.pyc,,
|
| 87 |
+
narwhals/_compliant/any_namespace.py,sha256=1Zbv6m0x21qbHJqG5YbhlmPDBKWS0XcGdqbm6s5Rwgk,4411
|
| 88 |
+
narwhals/_compliant/column.py,sha256=d5watE0NL3f9tsIMqpELlI5OYIeKSMYKqZg1JAEZBEQ,5273
|
| 89 |
+
narwhals/_compliant/dataframe.py,sha256=FlbZXtq3xuN1YlAXH7mUUZnEljeAv00gs6xyVoO3Pss,16819
|
| 90 |
+
narwhals/_compliant/expr.py,sha256=YayC8nTW1BKfTEpK6k5P_K1IuGbcsRh3r9kTYO1yaxM,42125
|
| 91 |
+
narwhals/_compliant/group_by.py,sha256=0eKCV-jxXe506ZVGRDQnoL0LsBeMMUHgqkalHkO8VQo,7050
|
| 92 |
+
narwhals/_compliant/namespace.py,sha256=ai7Tj7tGeWPBYNd7Bbkxvz-Y7zVKcqQW-y1j-RX3PPk,11348
|
| 93 |
+
narwhals/_compliant/selectors.py,sha256=und99_KqUg9zrdhBlfxQVl_6R-VPv6NsL3vv6Bcwhuk,11902
|
| 94 |
+
narwhals/_compliant/series.py,sha256=g4kTQv140Hykaon14-VZazPgdjMmVPCezqmQiHbt-RY,13790
|
| 95 |
+
narwhals/_compliant/typing.py,sha256=xQ6omwtoRfLCiGXlgh-o7FuR_zHwmxL_QEvp6S0EZ1U,7498
|
| 96 |
+
narwhals/_compliant/window.py,sha256=_ji4goVKkT4YPTyZa_I0N2yGmwBfB1_LDG0WSXGbmlo,505
|
| 97 |
+
narwhals/_constants.py,sha256=kE1KWsIky4ryabH-Z117ZtGW24ccTcreWOZJjpacO6I,1094
|
| 98 |
+
narwhals/_dask/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 99 |
+
narwhals/_dask/__pycache__/__init__.cpython-312.pyc,,
|
| 100 |
+
narwhals/_dask/__pycache__/dataframe.cpython-312.pyc,,
|
| 101 |
+
narwhals/_dask/__pycache__/expr.cpython-312.pyc,,
|
| 102 |
+
narwhals/_dask/__pycache__/expr_dt.cpython-312.pyc,,
|
| 103 |
+
narwhals/_dask/__pycache__/expr_str.cpython-312.pyc,,
|
| 104 |
+
narwhals/_dask/__pycache__/group_by.cpython-312.pyc,,
|
| 105 |
+
narwhals/_dask/__pycache__/namespace.cpython-312.pyc,,
|
| 106 |
+
narwhals/_dask/__pycache__/selectors.cpython-312.pyc,,
|
| 107 |
+
narwhals/_dask/__pycache__/utils.cpython-312.pyc,,
|
| 108 |
+
narwhals/_dask/dataframe.py,sha256=tCT7sjZQ-5s3ykXJI-U-dIvQjIWukvf2MoroHEx_g6A,19856
|
| 109 |
+
narwhals/_dask/expr.py,sha256=VSd6j1ucRuFXkkiEg6hsVs7LLxo-wN3b9bFSrhFNa78,26735
|
| 110 |
+
narwhals/_dask/expr_dt.py,sha256=gtLt-UgD0Kw_Vev32rOZUdmP_XQfvU9XrKjtgmkQYps,6276
|
| 111 |
+
narwhals/_dask/expr_str.py,sha256=XE6bKZd-PTfMsZOJ49mWzl1miiQQoKQlTG2U_i97gic,3885
|
| 112 |
+
narwhals/_dask/group_by.py,sha256=nwgSODQljSjJ10snNGvOvKN3ctBXNertD6pciA5H0cs,5083
|
| 113 |
+
narwhals/_dask/namespace.py,sha256=lfE8aXPwpb7ejdIhkxE5kFZy4GasGGrYEqraRaxpTBE,13416
|
| 114 |
+
narwhals/_dask/selectors.py,sha256=W8tLFVUbafUb5EKi5rg09-cP9JA4T3MwiIjKCYk1YH0,927
|
| 115 |
+
narwhals/_dask/utils.py,sha256=pAUYw9k1krePgRzGWxWVBj4OyMaT6AALaRILOR6ehxo,5445
|
| 116 |
+
narwhals/_duckdb/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 117 |
+
narwhals/_duckdb/__pycache__/__init__.cpython-312.pyc,,
|
| 118 |
+
narwhals/_duckdb/__pycache__/dataframe.cpython-312.pyc,,
|
| 119 |
+
narwhals/_duckdb/__pycache__/expr.cpython-312.pyc,,
|
| 120 |
+
narwhals/_duckdb/__pycache__/expr_dt.cpython-312.pyc,,
|
| 121 |
+
narwhals/_duckdb/__pycache__/expr_list.cpython-312.pyc,,
|
| 122 |
+
narwhals/_duckdb/__pycache__/expr_str.cpython-312.pyc,,
|
| 123 |
+
narwhals/_duckdb/__pycache__/expr_struct.cpython-312.pyc,,
|
| 124 |
+
narwhals/_duckdb/__pycache__/group_by.cpython-312.pyc,,
|
| 125 |
+
narwhals/_duckdb/__pycache__/namespace.cpython-312.pyc,,
|
| 126 |
+
narwhals/_duckdb/__pycache__/selectors.cpython-312.pyc,,
|
| 127 |
+
narwhals/_duckdb/__pycache__/series.cpython-312.pyc,,
|
| 128 |
+
narwhals/_duckdb/__pycache__/typing.cpython-312.pyc,,
|
| 129 |
+
narwhals/_duckdb/__pycache__/utils.cpython-312.pyc,,
|
| 130 |
+
narwhals/_duckdb/dataframe.py,sha256=SjQP-dj-XAd_lRCLqDmH-hHWT74yypUwvy9bNFEI4Bw,20462
|
| 131 |
+
narwhals/_duckdb/expr.py,sha256=k35p2V98KcjhMchjvdvkowap7Sw8WBrbVAFXPcej4wc,12486
|
| 132 |
+
narwhals/_duckdb/expr_dt.py,sha256=RDqYnsM0pDPEh59hq0BHrl6YNLFBR7w8gLIdxVWdzvY,5157
|
| 133 |
+
narwhals/_duckdb/expr_list.py,sha256=OgnTsvii5lJDZ2vBJQIXBGT0hMqK2HfGOX_Dvrli2es,2734
|
| 134 |
+
narwhals/_duckdb/expr_str.py,sha256=ksmAAAnRr9fE5dzLI8ZkcIkxCdv-o1lbE3k9zlVsv7k,1870
|
| 135 |
+
narwhals/_duckdb/expr_struct.py,sha256=eN06QA1JS6wjAt7_AZzW3xoztHM_hoadlFUl_hwsEiE,576
|
| 136 |
+
narwhals/_duckdb/group_by.py,sha256=e07h9TN45G6HUveqhalRDKp9PngacCRLa-o3WlkoW5o,1276
|
| 137 |
+
narwhals/_duckdb/namespace.py,sha256=g-4cU0j3CVwe4ljTc4brdYRoNSJM18b6g3vnvCY4EKQ,6400
|
| 138 |
+
narwhals/_duckdb/selectors.py,sha256=yA16Z-MlJUJBjOu0XI9qVO4Zx7L_T5FN2DQqNAYhu-o,1033
|
| 139 |
+
narwhals/_duckdb/series.py,sha256=xBpuPUnSSIQ1vYEKjHQFZN7ix1ZyMwSchliDPpkf3Wk,1397
|
| 140 |
+
narwhals/_duckdb/typing.py,sha256=gO_Odyinkn4QZY_TU4uuzda6mbeo38glOOUUripcWgg,454
|
| 141 |
+
narwhals/_duckdb/utils.py,sha256=yqg4XsFY_URuzEMBxew2a8aDdgHD2FMXfBBXqA-Bbz4,15810
|
| 142 |
+
narwhals/_duration.py,sha256=WGzj3FVcC2KogqRhNeim3YDIwUn8HkXQHAljtvHrjwQ,3139
|
| 143 |
+
narwhals/_enum.py,sha256=6mWLGvqHP8JhLRhBjGof4Ungx-SDasqu-G0M2pX0Oew,1142
|
| 144 |
+
narwhals/_exceptions.py,sha256=uVgFKgx_6ub9MHJ_qJ7xC5zie-uRVtbJo0j3FDoXAqk,1894
|
| 145 |
+
narwhals/_expression_parsing.py,sha256=M-GhKye9mecJLjI9lF3jiDVSQWijZ0j2nH6-DkPSYKc,33387
|
| 146 |
+
narwhals/_ibis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 147 |
+
narwhals/_ibis/__pycache__/__init__.cpython-312.pyc,,
|
| 148 |
+
narwhals/_ibis/__pycache__/dataframe.cpython-312.pyc,,
|
| 149 |
+
narwhals/_ibis/__pycache__/expr.cpython-312.pyc,,
|
| 150 |
+
narwhals/_ibis/__pycache__/expr_dt.cpython-312.pyc,,
|
| 151 |
+
narwhals/_ibis/__pycache__/expr_list.cpython-312.pyc,,
|
| 152 |
+
narwhals/_ibis/__pycache__/expr_str.cpython-312.pyc,,
|
| 153 |
+
narwhals/_ibis/__pycache__/expr_struct.cpython-312.pyc,,
|
| 154 |
+
narwhals/_ibis/__pycache__/group_by.cpython-312.pyc,,
|
| 155 |
+
narwhals/_ibis/__pycache__/namespace.cpython-312.pyc,,
|
| 156 |
+
narwhals/_ibis/__pycache__/selectors.cpython-312.pyc,,
|
| 157 |
+
narwhals/_ibis/__pycache__/series.cpython-312.pyc,,
|
| 158 |
+
narwhals/_ibis/__pycache__/utils.cpython-312.pyc,,
|
| 159 |
+
narwhals/_ibis/dataframe.py,sha256=ihqiWfvAeCRs3Vlcyj75yAel-Z4lGR8IL4g80MjX2cU,16388
|
| 160 |
+
narwhals/_ibis/expr.py,sha256=2Unv20zbWJ52goEPNIlq7zCKXtfDC9Z_B044G54BY_g,14018
|
| 161 |
+
narwhals/_ibis/expr_dt.py,sha256=0RS1B1geFYxyS5RplyG9VES8mFg4tylcG75dIKczvNs,3308
|
| 162 |
+
narwhals/_ibis/expr_list.py,sha256=1REKJRa7930JTMofZbSb4rghjBg1mOAZf8sRcKx1EUs,2343
|
| 163 |
+
narwhals/_ibis/expr_str.py,sha256=fvYzDibIaGH8bE3ZhTUF9yfs--0ONM6l7f5zeW7neLk,3443
|
| 164 |
+
narwhals/_ibis/expr_struct.py,sha256=FDsa5MqcHhqPmpZIEfGBASdqxPkyImrlGTH7XUSw3cs,565
|
| 165 |
+
narwhals/_ibis/group_by.py,sha256=enNzAPUsA_LIwPNJ7jG_MJKyqG2HyCiesBEX3pJgJBg,1031
|
| 166 |
+
narwhals/_ibis/namespace.py,sha256=H3d9nO20RAEF0UVQzBaN4jHkSmk3JHR2iV2tP26uzKE,5635
|
| 167 |
+
narwhals/_ibis/selectors.py,sha256=SkFxoukpKc_OjwKoKHRm8VwMaphCMUeWBJ2g_oWz3D0,961
|
| 168 |
+
narwhals/_ibis/series.py,sha256=CZDwDPsdELKtdr7OWmcFyGqexr33Ucfnv_RU95VJxIQ,1218
|
| 169 |
+
narwhals/_ibis/utils.py,sha256=j2nf-cb3wXP0OOlMuyg3qMsFOYZHD_c5pnW_qwu4uy0,10591
|
| 170 |
+
narwhals/_interchange/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 171 |
+
narwhals/_interchange/__pycache__/__init__.cpython-312.pyc,,
|
| 172 |
+
narwhals/_interchange/__pycache__/dataframe.cpython-312.pyc,,
|
| 173 |
+
narwhals/_interchange/__pycache__/series.cpython-312.pyc,,
|
| 174 |
+
narwhals/_interchange/dataframe.py,sha256=FC_2WuxxI4RPUBMqcau68rkdfsxhClou4zCErx1flcw,6034
|
| 175 |
+
narwhals/_interchange/series.py,sha256=nSxdlOZrw3wtavS42TMR_b_EGgPBv224ioZBMo5eoC8,1651
|
| 176 |
+
narwhals/_namespace.py,sha256=ARbIk31MgCvYDAxlAz7J9TGKktG0_p-Eu9myDi3nurs,8551
|
| 177 |
+
narwhals/_native.py,sha256=ByNgFo_kGIsgr_dSte8mT6snLjiBbsvAFGrECnXjl-g,15402
|
| 178 |
+
narwhals/_pandas_like/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 179 |
+
narwhals/_pandas_like/__pycache__/__init__.cpython-312.pyc,,
|
| 180 |
+
narwhals/_pandas_like/__pycache__/dataframe.cpython-312.pyc,,
|
| 181 |
+
narwhals/_pandas_like/__pycache__/expr.cpython-312.pyc,,
|
| 182 |
+
narwhals/_pandas_like/__pycache__/group_by.cpython-312.pyc,,
|
| 183 |
+
narwhals/_pandas_like/__pycache__/namespace.cpython-312.pyc,,
|
| 184 |
+
narwhals/_pandas_like/__pycache__/selectors.cpython-312.pyc,,
|
| 185 |
+
narwhals/_pandas_like/__pycache__/series.cpython-312.pyc,,
|
| 186 |
+
narwhals/_pandas_like/__pycache__/series_cat.cpython-312.pyc,,
|
| 187 |
+
narwhals/_pandas_like/__pycache__/series_dt.cpython-312.pyc,,
|
| 188 |
+
narwhals/_pandas_like/__pycache__/series_list.cpython-312.pyc,,
|
| 189 |
+
narwhals/_pandas_like/__pycache__/series_str.cpython-312.pyc,,
|
| 190 |
+
narwhals/_pandas_like/__pycache__/series_struct.cpython-312.pyc,,
|
| 191 |
+
narwhals/_pandas_like/__pycache__/typing.cpython-312.pyc,,
|
| 192 |
+
narwhals/_pandas_like/__pycache__/utils.cpython-312.pyc,,
|
| 193 |
+
narwhals/_pandas_like/dataframe.py,sha256=S7yOLQzPJkDD0_WG3FRFNXHGi1slBusZ_sFtZlavNbo,46397
|
| 194 |
+
narwhals/_pandas_like/expr.py,sha256=8S2dcPNbB-PpsxWloB_PTVAIg5-wiKXMGHrSws9Eznw,16990
|
| 195 |
+
narwhals/_pandas_like/group_by.py,sha256=09zHMYyVXnQBM7efTHbWYMO4a-QdUYcVBfO3kY9oWjg,15484
|
| 196 |
+
narwhals/_pandas_like/namespace.py,sha256=hEs23p2AqNEp_NqPp_ZCYY9s_geiIuMCJgJ8_hH80mk,17025
|
| 197 |
+
narwhals/_pandas_like/selectors.py,sha256=ksx2a0Pf1g2OJu2dsWGnuUH3095v40OnhzT7zkolfhA,1015
|
| 198 |
+
narwhals/_pandas_like/series.py,sha256=hNPg9jRyDUon9UDJ1xgklako2Dn--cUBfldnBFw_llE,48087
|
| 199 |
+
narwhals/_pandas_like/series_cat.py,sha256=MJwCnJ49hfnODh6JgMHOCQ2KBlTbmySU6_X4XWaqiz4,527
|
| 200 |
+
narwhals/_pandas_like/series_dt.py,sha256=Mq6Dhrki-HoV2yqnbsKWT60W2li1UjtOTnKB5V3FTzA,11814
|
| 201 |
+
narwhals/_pandas_like/series_list.py,sha256=Ew6nc4z3cddOWDAwj-8s-ouHew7Eq9mTQbb55iw7JGI,2960
|
| 202 |
+
narwhals/_pandas_like/series_str.py,sha256=XCX1xE2-GjV5E6VVQWQXVmuyS7UNuG3e5jhgwaDu4ek,4875
|
| 203 |
+
narwhals/_pandas_like/series_struct.py,sha256=vX9HoO42vHackvVozUfp8odM9uJ4owct49ydKDnohdk,518
|
| 204 |
+
narwhals/_pandas_like/typing.py,sha256=4-y2QKdz3GChKp8HStqFLW8Fwe5KUMFFJDtjGR76ERQ,1059
|
| 205 |
+
narwhals/_pandas_like/utils.py,sha256=DBFU2dBqxbaXBP2mClNEGMuL_0hByOsn4yLnUHZLmPE,26543
|
| 206 |
+
narwhals/_polars/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 207 |
+
narwhals/_polars/__pycache__/__init__.cpython-312.pyc,,
|
| 208 |
+
narwhals/_polars/__pycache__/dataframe.cpython-312.pyc,,
|
| 209 |
+
narwhals/_polars/__pycache__/expr.cpython-312.pyc,,
|
| 210 |
+
narwhals/_polars/__pycache__/group_by.cpython-312.pyc,,
|
| 211 |
+
narwhals/_polars/__pycache__/namespace.cpython-312.pyc,,
|
| 212 |
+
narwhals/_polars/__pycache__/series.cpython-312.pyc,,
|
| 213 |
+
narwhals/_polars/__pycache__/typing.cpython-312.pyc,,
|
| 214 |
+
narwhals/_polars/__pycache__/utils.cpython-312.pyc,,
|
| 215 |
+
narwhals/_polars/dataframe.py,sha256=vTeRBVrS103xVvdGhHJ8Hs31WCpuBGle421Csbi7dYI,26141
|
| 216 |
+
narwhals/_polars/expr.py,sha256=QdRHd7aKjEO1J595zzp4jwLq5lOqoO5c7yPDjB1dcB0,17882
|
| 217 |
+
narwhals/_polars/group_by.py,sha256=PsxQPWX7QWy2iXUWJEelC5O6mR1TKr9MB_i6O5RVxms,2373
|
| 218 |
+
narwhals/_polars/namespace.py,sha256=AFRy05M9TLzYlJVwwKlk1YN7Mb8EWdAc7i132CjGblE,10469
|
| 219 |
+
narwhals/_polars/series.py,sha256=Pdp4B1k6AR4moNWugq4xTUvkHJQizz04wzE1ZAEfaf4,28502
|
| 220 |
+
narwhals/_polars/typing.py,sha256=d11nVYqv1dqC_H2A-PXz1oHYYCAOnkK_s87ytm4twMA,302
|
| 221 |
+
narwhals/_polars/utils.py,sha256=NcNC8kPirVuo3FRVtOcoXMPIfElikdwQ05nfR49flLM,13035
|
| 222 |
+
narwhals/_spark_like/__init__.py,sha256=T7_UCePrrYs1ZeMatvCUYUvQcXvrDjQ4b08_ugWIHAo,87
|
| 223 |
+
narwhals/_spark_like/__pycache__/__init__.cpython-312.pyc,,
|
| 224 |
+
narwhals/_spark_like/__pycache__/dataframe.cpython-312.pyc,,
|
| 225 |
+
narwhals/_spark_like/__pycache__/expr.cpython-312.pyc,,
|
| 226 |
+
narwhals/_spark_like/__pycache__/expr_dt.cpython-312.pyc,,
|
| 227 |
+
narwhals/_spark_like/__pycache__/expr_list.cpython-312.pyc,,
|
| 228 |
+
narwhals/_spark_like/__pycache__/expr_str.cpython-312.pyc,,
|
| 229 |
+
narwhals/_spark_like/__pycache__/expr_struct.cpython-312.pyc,,
|
| 230 |
+
narwhals/_spark_like/__pycache__/group_by.cpython-312.pyc,,
|
| 231 |
+
narwhals/_spark_like/__pycache__/namespace.cpython-312.pyc,,
|
| 232 |
+
narwhals/_spark_like/__pycache__/selectors.cpython-312.pyc,,
|
| 233 |
+
narwhals/_spark_like/__pycache__/utils.cpython-312.pyc,,
|
| 234 |
+
narwhals/_spark_like/dataframe.py,sha256=tcQSJl1RO6i1DuV4bsji1mHWSqHLOy5CAC3UoVsP3tY,23329
|
| 235 |
+
narwhals/_spark_like/expr.py,sha256=oBtmPMTlS356IoDQ47HXzCujDqmh4QXgQQn2le71qC4,15337
|
| 236 |
+
narwhals/_spark_like/expr_dt.py,sha256=EuvgesSi-N4DN3F3zRy9kS2So6gx-w7bxlGbyrJieBU,7874
|
| 237 |
+
narwhals/_spark_like/expr_list.py,sha256=1B9OsYCXYEWJqIUm5Id2ikMMKNTwoCyeia5LXRYp-OA,3853
|
| 238 |
+
narwhals/_spark_like/expr_str.py,sha256=iM2nmJpIeNQP8v5W9kyug1wlVir3cM8VDXHVGyHQMPU,2452
|
| 239 |
+
narwhals/_spark_like/expr_struct.py,sha256=haBDpuRhn_nGAFjMF3arhhRr6NfefNei9vEmAOa0fQI,613
|
| 240 |
+
narwhals/_spark_like/group_by.py,sha256=DH7fgToOMLaQXEVPSkMjqzTpdz2ZjDIAM0WoK8XjQFU,1247
|
| 241 |
+
narwhals/_spark_like/namespace.py,sha256=k1UTQez8qMdgQRj6H8yi4jEcAqhZe7a8w83PwVaFLlk,8522
|
| 242 |
+
narwhals/_spark_like/selectors.py,sha256=SzJPoFjyIEviSSvPRvL81o1jjQJcM-Veqb52vFU66JQ,1086
|
| 243 |
+
narwhals/_spark_like/utils.py,sha256=hRQT2SDrKJfZrfFFqDhW-s8UVkfc0LcKuTjbgoeTcj0,11892
|
| 244 |
+
narwhals/_sql/__init__.py,sha256=T7_UCePrrYs1ZeMatvCUYUvQcXvrDjQ4b08_ugWIHAo,87
|
| 245 |
+
narwhals/_sql/__pycache__/__init__.cpython-312.pyc,,
|
| 246 |
+
narwhals/_sql/__pycache__/dataframe.cpython-312.pyc,,
|
| 247 |
+
narwhals/_sql/__pycache__/expr.cpython-312.pyc,,
|
| 248 |
+
narwhals/_sql/__pycache__/expr_dt.cpython-312.pyc,,
|
| 249 |
+
narwhals/_sql/__pycache__/expr_str.cpython-312.pyc,,
|
| 250 |
+
narwhals/_sql/__pycache__/group_by.cpython-312.pyc,,
|
| 251 |
+
narwhals/_sql/__pycache__/namespace.cpython-312.pyc,,
|
| 252 |
+
narwhals/_sql/__pycache__/typing.cpython-312.pyc,,
|
| 253 |
+
narwhals/_sql/dataframe.py,sha256=itTHoiLQ74S0Z8SeRgFT_Ss4jbWBs9La5DrME4Mm3xU,2451
|
| 254 |
+
narwhals/_sql/expr.py,sha256=-7VO3_RWNAmr-2YANZD0_K6EKD3_dBMUTMi1sHtqI20,34572
|
| 255 |
+
narwhals/_sql/expr_dt.py,sha256=QcBGKkp9_gUgPOMGXcfuGsqeC7iT1AAGrq5ZDX-nEKo,1700
|
| 256 |
+
narwhals/_sql/expr_str.py,sha256=RPsPIqySlNmAOOMGVai0nUnpUqhldc1X6jx-Bsnq6TM,7433
|
| 257 |
+
narwhals/_sql/group_by.py,sha256=-yR5J2-Kk0awFRoFnLici00rfTK_5CxFKJSxc-Bt8Zs,1669
|
| 258 |
+
narwhals/_sql/namespace.py,sha256=hvSGHpWebsx05PYipMQp8GRlM1Zx-_qCopPzhv7nbXo,3352
|
| 259 |
+
narwhals/_sql/typing.py,sha256=e3LkLPI4oa2IzykR7BgO9IIfCKRw0vrX4uHxPTB-uJM,487
|
| 260 |
+
narwhals/_translate.py,sha256=z9BXuXTI6YSjep4I1o9hRE35JT-7sLGt8Z9GF01GhRc,9389
|
| 261 |
+
narwhals/_typing.py,sha256=eneOfgi2z_4rGbYnvT_IWmEyMgSUhWrTZ1kaGFWVLNQ,6497
|
| 262 |
+
narwhals/_typing_compat.py,sha256=h-BtLEl7CrZ-hYLlwYTOcCdsUS3dvgvkxQTcDQ7RYmA,2516
|
| 263 |
+
narwhals/_utils.py,sha256=0P_V4Avv5NdS5HSJg_8ECjzQiadLoSlyEdYU6ekiynU,73287
|
| 264 |
+
narwhals/compliant.py,sha256=MYzN7r6qgieJjw68g4I-HKXum0r_fhlf1vAlfRL47yk,920
|
| 265 |
+
narwhals/dataframe.py,sha256=ChwNNRfP78bDtQMlC6FP_Y0f869avDcRCHvAuWwBxq4,137172
|
| 266 |
+
narwhals/dependencies.py,sha256=ABk7GskzfO4JnEBoH4WotfEEYR3KylOqY8anDjt8140,19926
|
| 267 |
+
narwhals/dtypes.py,sha256=iFv3WabAXslxxDd3ZHshkbLXuTvKNFV4kY7EvoeFAcE,33117
|
| 268 |
+
narwhals/exceptions.py,sha256=97IIfR_YmJYZEb53uwoARpegXleq-Im3QMDjZs7thGo,3758
|
| 269 |
+
narwhals/expr.py,sha256=YB1pRIzmMsfZh3D9qW913EAo-LbQMeMoCn_jdx07Xns,110482
|
| 270 |
+
narwhals/expr_cat.py,sha256=Rfyy4Q_oyFmfz2enTebUY2MCQtwA8ZtBFmhUpQ295UU,1250
|
| 271 |
+
narwhals/expr_dt.py,sha256=FFPj3KcdgZrvv4M7-_IKPvivv5GZFTbjsnULxOB3_6Q,31816
|
| 272 |
+
narwhals/expr_list.py,sha256=K99FGLW9IYeK7NRiVKrICJ6NseQJl86YJcf47sfdHPw,14228
|
| 273 |
+
narwhals/expr_name.py,sha256=yhMal_7caymLduWhTs1NRYb5y35bincnoZK5gCQWX5U,4814
|
| 274 |
+
narwhals/expr_str.py,sha256=b45kQ86rDc5oBETxqw_QXKFEKRJ0E6X9DC40o8wgmic,25270
|
| 275 |
+
narwhals/expr_struct.py,sha256=9sHY743_UDsduwgUfip4X_xs-_A-aCHSVdlMsDk8WNA,1790
|
| 276 |
+
narwhals/functions.py,sha256=q4slLkkjBV-17bPPiTDStZi8TETJ7WrMHixtHM6KMgw,71617
|
| 277 |
+
narwhals/group_by.py,sha256=JLE0hEdi_-0dVAL_ayby7DqUUbxQjSMwBsIh0Cb0OtY,6632
|
| 278 |
+
narwhals/plugins.py,sha256=8ZIhps5rCUgf9ilwvmtgqO4sMOaSaRSekvixlLyzRxg,3878
|
| 279 |
+
narwhals/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 280 |
+
narwhals/schema.py,sha256=4yiRz6Qv373ATpN6kCFNSblUb4vMDX9USpKeJTDRrYI,12369
|
| 281 |
+
narwhals/selectors.py,sha256=Wig5bbVEE8IYYlErkH_xIeTykC6x7tDb1eXqUDlLfBc,10200
|
| 282 |
+
narwhals/series.py,sha256=ET5N0CkDXu4FdcMi7XKQbYPhRWPdAEMGgsNRVH6_grA,103178
|
| 283 |
+
narwhals/series_cat.py,sha256=mikr2q3S8kWo8uTJ4s2z6ZKv9cgn-jC1xNy_tYQaQyw,831
|
| 284 |
+
narwhals/series_dt.py,sha256=O3ZRXCPbwtQbcyqahyNBw3PMMhJAGMd732pSYjGaF4c,23051
|
| 285 |
+
narwhals/series_list.py,sha256=8QsdcP_HGrvcu-w-l_WT28o_tJ2_C7xKWaN5sCf9-_g,7954
|
| 286 |
+
narwhals/series_str.py,sha256=dPKgIEyb1BP6l1hW4Hl8RsngKPWayXcaWdamkbjuxU0,19378
|
| 287 |
+
narwhals/series_struct.py,sha256=bixxdASlxYyP1prDjMmfltVU5212a596VQZE11yszUg,930
|
| 288 |
+
narwhals/sql.py,sha256=MhWT4E3S4gV4fiQCmVlFd6k01irkF4aJhbpzOEdQIas,3767
|
| 289 |
+
narwhals/stable/__init__.py,sha256=WX57ijebHmAZMq_ngLYyOZFTxiBc99dnxldiXkBDccQ,95
|
| 290 |
+
narwhals/stable/__pycache__/__init__.cpython-312.pyc,,
|
| 291 |
+
narwhals/stable/v1/__init__.py,sha256=twpERqdSTJfqf0EC8gZ0kJrxVXRLuC3Z2BlkzgJXpUY,36571
|
| 292 |
+
narwhals/stable/v1/__pycache__/__init__.cpython-312.pyc,,
|
| 293 |
+
narwhals/stable/v1/__pycache__/_dtypes.cpython-312.pyc,,
|
| 294 |
+
narwhals/stable/v1/__pycache__/_namespace.cpython-312.pyc,,
|
| 295 |
+
narwhals/stable/v1/__pycache__/dependencies.cpython-312.pyc,,
|
| 296 |
+
narwhals/stable/v1/__pycache__/dtypes.cpython-312.pyc,,
|
| 297 |
+
narwhals/stable/v1/__pycache__/selectors.cpython-312.pyc,,
|
| 298 |
+
narwhals/stable/v1/__pycache__/typing.cpython-312.pyc,,
|
| 299 |
+
narwhals/stable/v1/_dtypes.py,sha256=ngGP8hQRdYv19GJgtynHPMEg-RUIDOs_jdbGrt5YO9E,2722
|
| 300 |
+
narwhals/stable/v1/_namespace.py,sha256=gfsbT4R4aLmmdArY35LRpEHPiUeZKEEnXGiY9ypFtwE,296
|
| 301 |
+
narwhals/stable/v1/dependencies.py,sha256=aM0IShF4hbaaMEDRJQXvsu4RABZOdBG4QhrpJPxb7fg,5001
|
| 302 |
+
narwhals/stable/v1/dtypes.py,sha256=u2NFDJyCkjsK6p3K9ULJS7CoG16z0Z1MQiACTVkhkH4,1082
|
| 303 |
+
narwhals/stable/v1/selectors.py,sha256=xEA9bBzkpTwUanGGoFwBCcHIAXb8alwrPX1mjzE9mDM,312
|
| 304 |
+
narwhals/stable/v1/typing.py,sha256=9YhcvKJ8jtN8mQBD0q12HShEM6Q-D10DYB-m4lQYzDM,4998
|
| 305 |
+
narwhals/stable/v2/__init__.py,sha256=7eG-5HA3p70dRpmNIG0SRk6A7bq9qahE9yOibwO2KmA,40312
|
| 306 |
+
narwhals/stable/v2/__pycache__/__init__.cpython-312.pyc,,
|
| 307 |
+
narwhals/stable/v2/__pycache__/_namespace.cpython-312.pyc,,
|
| 308 |
+
narwhals/stable/v2/__pycache__/dependencies.cpython-312.pyc,,
|
| 309 |
+
narwhals/stable/v2/__pycache__/dtypes.cpython-312.pyc,,
|
| 310 |
+
narwhals/stable/v2/__pycache__/selectors.cpython-312.pyc,,
|
| 311 |
+
narwhals/stable/v2/__pycache__/typing.cpython-312.pyc,,
|
| 312 |
+
narwhals/stable/v2/_namespace.py,sha256=oYB5nrFGxqqTonkRx9vUanyBxGs2Yb0j7_juMyvnvWA,296
|
| 313 |
+
narwhals/stable/v2/dependencies.py,sha256=vpYWx_dron6wFdbQ60G06EV2UJ_LMd52LDodCrAY5Jg,86
|
| 314 |
+
narwhals/stable/v2/dtypes.py,sha256=iMpk2Kc1mNiQYmboOSgmiAijklSUBHSHF2LTKMKnGe8,80
|
| 315 |
+
narwhals/stable/v2/selectors.py,sha256=sjJL3agHd8Rgf_lWhgCmEKruhWEkwHdX32-n85OqVJU,83
|
| 316 |
+
narwhals/stable/v2/typing.py,sha256=pAR_JL07FgNaLgCenpQVO3E0oFwYAi2wxCS2htgUJUs,2494
|
| 317 |
+
narwhals/testing/__init__.py,sha256=eCy8mtRcHySZiaWPV2r21DLZrznjtRQggj8ygoQms28,219
|
| 318 |
+
narwhals/testing/__pycache__/__init__.cpython-312.pyc,,
|
| 319 |
+
narwhals/testing/asserts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 320 |
+
narwhals/testing/asserts/__pycache__/__init__.cpython-312.pyc,,
|
| 321 |
+
narwhals/testing/asserts/__pycache__/frame.cpython-312.pyc,,
|
| 322 |
+
narwhals/testing/asserts/__pycache__/series.cpython-312.pyc,,
|
| 323 |
+
narwhals/testing/asserts/__pycache__/utils.cpython-312.pyc,,
|
| 324 |
+
narwhals/testing/asserts/frame.py,sha256=SUNo7tFyLcXEyEKK1SHaPmM6O99YSpGYKNf5kY3Obm8,10511
|
| 325 |
+
narwhals/testing/asserts/series.py,sha256=MWhbghtXnT7GX8hsOS31TkoX0TpmkLmsFReaUaPR1F8,11118
|
| 326 |
+
narwhals/testing/asserts/utils.py,sha256=3VLqrRONh5e_-sQfhweOEr7gDjvZISq_o-XxGBn4mrU,2188
|
| 327 |
+
narwhals/this.py,sha256=BbKcj0ReWqE01lznzKjuqq7otXONvjBevWWC5aJhQxs,1584
|
| 328 |
+
narwhals/translate.py,sha256=YlS3UQWdU7JXbZq2ZcY1HVPBQLAKIMFhlY3AOQ_67cM,24169
|
| 329 |
+
narwhals/typing.py,sha256=2imWqcYKdpbSfjjNtwNSQ1Y_hm078_rre1cGX0ox3qg,13970
|
| 330 |
+
narwhals/utils.py,sha256=2GT3XxucWI6l9r9jTwMw7Aha2G73FsSXgXNFZ3O_ZyA,223
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.29.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/licenses/._LICENSE.md
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/licenses/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2024 to present, Marco Gorelli
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
.venv_haddock/lib/python3.12/site-packages/narwhals/dataframe.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/dependencies.py
ADDED
|
@@ -0,0 +1,631 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pandas / Polars / etc. : if a user passes a dataframe from one of these
|
| 2 |
+
# libraries, it means they must already have imported the given module.
|
| 3 |
+
# So, we can just check sys.modules.
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
from typing import TYPE_CHECKING, Any
|
| 8 |
+
|
| 9 |
+
from narwhals._exceptions import issue_warning
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
import cudf
|
| 13 |
+
import dask.dataframe as dd
|
| 14 |
+
import duckdb
|
| 15 |
+
import ibis
|
| 16 |
+
import modin.pandas as mpd
|
| 17 |
+
import pandas as pd
|
| 18 |
+
import polars as pl
|
| 19 |
+
import pyarrow as pa
|
| 20 |
+
import pyspark.sql as pyspark_sql
|
| 21 |
+
from pyspark.sql.connect.dataframe import DataFrame as PySparkConnectDataFrame
|
| 22 |
+
from typing_extensions import TypeGuard, TypeIs
|
| 23 |
+
|
| 24 |
+
from narwhals._spark_like.dataframe import SQLFrameDataFrame
|
| 25 |
+
from narwhals.dataframe import DataFrame, LazyFrame
|
| 26 |
+
from narwhals.series import Series
|
| 27 |
+
from narwhals.typing import (
|
| 28 |
+
IntoDataFrameT,
|
| 29 |
+
IntoLazyFrameT,
|
| 30 |
+
IntoSeriesT,
|
| 31 |
+
PandasLikeDType,
|
| 32 |
+
_1DArray,
|
| 33 |
+
_1DArrayInt,
|
| 34 |
+
_2DArray,
|
| 35 |
+
_NDArray,
|
| 36 |
+
_NumpyScalar,
|
| 37 |
+
_ShapeT,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# We silently allow these but - given that they claim
|
| 42 |
+
# to be drop-in replacements for pandas - testing is
|
| 43 |
+
# their responsibility.
|
| 44 |
+
IMPORT_HOOKS = frozenset(["fireducks"])
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_polars() -> Any:
|
| 48 |
+
"""Get Polars module (if already imported - else return None)."""
|
| 49 |
+
return sys.modules.get("polars", None)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_pandas() -> Any:
|
| 53 |
+
"""Get pandas module (if already imported - else return None)."""
|
| 54 |
+
return sys.modules.get("pandas", None)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_modin() -> Any: # pragma: no cover
|
| 58 |
+
"""Get modin.pandas module (if already imported - else return None)."""
|
| 59 |
+
return sys.modules.get("modin.pandas", None)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def get_cudf() -> Any:
|
| 63 |
+
"""Get cudf module (if already imported - else return None)."""
|
| 64 |
+
return sys.modules.get("cudf", None)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_cupy() -> Any:
|
| 68 |
+
"""Get cupy module (if already imported - else return None)."""
|
| 69 |
+
return sys.modules.get("cupy", None)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def get_pyarrow() -> Any: # pragma: no cover
|
| 73 |
+
"""Get pyarrow module (if already imported - else return None)."""
|
| 74 |
+
return sys.modules.get("pyarrow", None)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_numpy() -> Any:
|
| 78 |
+
"""Get numpy module (if already imported - else return None)."""
|
| 79 |
+
return sys.modules.get("numpy", None)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_dask() -> Any: # pragma: no cover
|
| 83 |
+
"""Get dask (if already imported - else return None)."""
|
| 84 |
+
return sys.modules.get("dask", None)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def get_dask_dataframe() -> Any:
|
| 88 |
+
"""Get dask.dataframe module (if already imported - else return None)."""
|
| 89 |
+
return sys.modules.get("dask.dataframe", None)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def get_duckdb() -> Any:
|
| 93 |
+
"""Get duckdb module (if already imported - else return None)."""
|
| 94 |
+
return sys.modules.get("duckdb", None)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def get_ibis() -> Any:
|
| 98 |
+
"""Get ibis module (if already imported - else return None)."""
|
| 99 |
+
return sys.modules.get("ibis", None)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_dask_expr() -> Any: # pragma: no cover
|
| 103 |
+
"""Get dask_expr module (if already imported - else return None)."""
|
| 104 |
+
if (dd := get_dask_dataframe()) is not None and hasattr(dd, "dask_expr"):
|
| 105 |
+
return dd.dask_expr
|
| 106 |
+
return sys.modules.get("dask_expr", None)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def get_pyspark() -> Any: # pragma: no cover
|
| 110 |
+
"""Get pyspark module (if already imported - else return None)."""
|
| 111 |
+
return sys.modules.get("pyspark", None)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def get_pyspark_sql() -> Any:
|
| 115 |
+
"""Get pyspark.sql module (if already imported - else return None)."""
|
| 116 |
+
return sys.modules.get("pyspark.sql", None)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def get_pyspark_connect() -> Any:
|
| 120 |
+
"""Get pyspark.sql.connect module (if already imported - else return None)."""
|
| 121 |
+
return sys.modules.get("pyspark.sql.connect", None)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def get_sqlframe() -> Any:
|
| 125 |
+
"""Get sqlframe module (if already imported - else return None)."""
|
| 126 |
+
return sys.modules.get("sqlframe", None)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _warn_if_narwhals_df_or_lf(df: Any) -> None:
|
| 130 |
+
if is_narwhals_dataframe(df) or is_narwhals_lazyframe(df):
|
| 131 |
+
msg = (
|
| 132 |
+
f"You passed a `{type(df)}` to `is_pandas_dataframe`.\n\n"
|
| 133 |
+
"Hint: Instead of e.g. `is_pandas_dataframe(df)`, "
|
| 134 |
+
"did you mean `is_pandas_dataframe(df.to_native())`?"
|
| 135 |
+
)
|
| 136 |
+
issue_warning(msg, UserWarning)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _warn_if_narwhals_series(ser: Any) -> None:
|
| 140 |
+
if is_narwhals_series(ser):
|
| 141 |
+
msg = (
|
| 142 |
+
f"You passed a `{type(ser)}` to `is_pandas_series`.\n\n"
|
| 143 |
+
"Hint: Instead of e.g. `is_pandas_series(ser)`, "
|
| 144 |
+
"did you mean `is_pandas_series(ser.to_native())`?"
|
| 145 |
+
)
|
| 146 |
+
issue_warning(msg, UserWarning)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def is_pandas_dataframe(df: Any) -> TypeIs[pd.DataFrame]:
|
| 150 |
+
"""Check whether `df` is a pandas DataFrame without importing pandas.
|
| 151 |
+
|
| 152 |
+
Warning:
|
| 153 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 154 |
+
"""
|
| 155 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 156 |
+
return ((pd := get_pandas()) is not None and isinstance(df, pd.DataFrame)) or any(
|
| 157 |
+
(mod := sys.modules.get(module_name, None)) is not None
|
| 158 |
+
and isinstance(df, mod.pandas.DataFrame)
|
| 159 |
+
for module_name in IMPORT_HOOKS
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def is_pandas_series(ser: Any) -> TypeIs[pd.Series[Any]]:
|
| 164 |
+
"""Check whether `ser` is a pandas Series without importing pandas.
|
| 165 |
+
|
| 166 |
+
Warning:
|
| 167 |
+
This method cannot be called on Narwhals Series.
|
| 168 |
+
"""
|
| 169 |
+
_warn_if_narwhals_series(ser)
|
| 170 |
+
return ((pd := get_pandas()) is not None and isinstance(ser, pd.Series)) or any(
|
| 171 |
+
(mod := sys.modules.get(module_name, None)) is not None
|
| 172 |
+
and isinstance(ser, mod.pandas.Series)
|
| 173 |
+
for module_name in IMPORT_HOOKS
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def is_pandas_index(index: Any) -> TypeIs[pd.Index[Any]]:
|
| 178 |
+
"""Check whether `index` is a pandas Index without importing pandas."""
|
| 179 |
+
return ((pd := get_pandas()) is not None and isinstance(index, pd.Index)) or any(
|
| 180 |
+
(mod := sys.modules.get(module_name, None)) is not None
|
| 181 |
+
and isinstance(index, mod.pandas.Index)
|
| 182 |
+
for module_name in IMPORT_HOOKS
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def is_modin_dataframe(df: Any) -> TypeIs[mpd.DataFrame]:
|
| 187 |
+
"""Check whether `df` is a modin DataFrame without importing modin.
|
| 188 |
+
|
| 189 |
+
Warning:
|
| 190 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 191 |
+
"""
|
| 192 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 193 |
+
return (mpd := get_modin()) is not None and isinstance(df, mpd.DataFrame)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def is_modin_series(ser: Any) -> TypeIs[mpd.Series]:
|
| 197 |
+
"""Check whether `ser` is a modin Series without importing modin.
|
| 198 |
+
|
| 199 |
+
Warning:
|
| 200 |
+
This method cannot be called on Narwhals Series.
|
| 201 |
+
"""
|
| 202 |
+
_warn_if_narwhals_series(ser)
|
| 203 |
+
return (mpd := get_modin()) is not None and isinstance(ser, mpd.Series)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def is_modin_index(index: Any) -> TypeIs[mpd.Index[Any]]: # pragma: no cover
|
| 207 |
+
"""Check whether `index` is a modin Index without importing modin."""
|
| 208 |
+
return (mpd := get_modin()) is not None and isinstance(index, mpd.Index)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def is_cudf_dataframe(df: Any) -> TypeIs[cudf.DataFrame]:
|
| 212 |
+
"""Check whether `df` is a cudf DataFrame without importing cudf.
|
| 213 |
+
|
| 214 |
+
Warning:
|
| 215 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 216 |
+
"""
|
| 217 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 218 |
+
return (cudf := get_cudf()) is not None and isinstance(df, cudf.DataFrame)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def is_cudf_series(ser: Any) -> TypeIs[cudf.Series[Any]]:
|
| 222 |
+
"""Check whether `ser` is a cudf Series without importing cudf.
|
| 223 |
+
|
| 224 |
+
Warning:
|
| 225 |
+
This method cannot be called on Narwhals Series.
|
| 226 |
+
"""
|
| 227 |
+
_warn_if_narwhals_series(ser)
|
| 228 |
+
return (cudf := get_cudf()) is not None and isinstance(ser, cudf.Series)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def is_cudf_index(index: Any) -> TypeIs[cudf.Index]:
|
| 232 |
+
"""Check whether `index` is a cudf Index without importing cudf."""
|
| 233 |
+
return (cudf := get_cudf()) is not None and isinstance(
|
| 234 |
+
index, cudf.Index
|
| 235 |
+
) # pragma: no cover
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def is_cupy_scalar(obj: Any) -> bool:
|
| 239 |
+
return (
|
| 240 |
+
(cupy := get_cupy()) is not None
|
| 241 |
+
and isinstance(obj, cupy.ndarray)
|
| 242 |
+
and obj.size == 1
|
| 243 |
+
) # pragma: no cover
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def is_dask_dataframe(df: Any) -> TypeIs[dd.DataFrame]:
|
| 247 |
+
"""Check whether `df` is a Dask DataFrame without importing Dask.
|
| 248 |
+
|
| 249 |
+
Warning:
|
| 250 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 251 |
+
"""
|
| 252 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 253 |
+
return (dd := get_dask_dataframe()) is not None and isinstance(df, dd.DataFrame)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def is_duckdb_relation(df: Any) -> TypeIs[duckdb.DuckDBPyRelation]:
|
| 257 |
+
"""Check whether `df` is a DuckDB Relation without importing DuckDB.
|
| 258 |
+
|
| 259 |
+
Warning:
|
| 260 |
+
This method cannot be called on Narwhals DataFrame/LazyFrame.
|
| 261 |
+
"""
|
| 262 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 263 |
+
return (duckdb := get_duckdb()) is not None and isinstance(
|
| 264 |
+
df, duckdb.DuckDBPyRelation
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def is_ibis_table(df: Any) -> TypeIs[ibis.Table]:
|
| 269 |
+
"""Check whether `df` is a Ibis Table without importing Ibis.
|
| 270 |
+
|
| 271 |
+
Warning:
|
| 272 |
+
This method cannot be called on Narwhals DataFrame/LazyFrame.
|
| 273 |
+
"""
|
| 274 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 275 |
+
return (ibis := get_ibis()) is not None and isinstance(df, ibis.expr.types.Table)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def is_polars_dataframe(df: Any) -> TypeIs[pl.DataFrame]:
|
| 279 |
+
"""Check whether `df` is a Polars DataFrame without importing Polars.
|
| 280 |
+
|
| 281 |
+
Warning:
|
| 282 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 283 |
+
"""
|
| 284 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 285 |
+
return (pl := get_polars()) is not None and isinstance(df, pl.DataFrame)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def is_polars_lazyframe(df: Any) -> TypeIs[pl.LazyFrame]:
|
| 289 |
+
"""Check whether `df` is a Polars LazyFrame without importing Polars.
|
| 290 |
+
|
| 291 |
+
Warning:
|
| 292 |
+
This method cannot be called on Narwhals DataFrame/LazyFrame.
|
| 293 |
+
"""
|
| 294 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 295 |
+
return (pl := get_polars()) is not None and isinstance(df, pl.LazyFrame)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def is_polars_series(ser: Any) -> TypeIs[pl.Series]:
|
| 299 |
+
"""Check whether `ser` is a Polars Series without importing Polars.
|
| 300 |
+
|
| 301 |
+
Warning:
|
| 302 |
+
This method cannot be called on Narwhals Series.
|
| 303 |
+
"""
|
| 304 |
+
_warn_if_narwhals_series(ser)
|
| 305 |
+
return (pl := get_polars()) is not None and isinstance(ser, pl.Series)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def is_polars_schema(obj: Any) -> TypeIs[pl.Schema]:
|
| 309 |
+
return (
|
| 310 |
+
bool(pl := get_polars()) and hasattr(pl, "Schema") and isinstance(obj, pl.Schema)
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# NOTE: For `pl.Schema` only instantiated dtypes are expected
|
| 315 |
+
def is_polars_data_type(obj: Any) -> TypeIs[pl.DataType]:
|
| 316 |
+
return bool(pl := get_polars()) and isinstance(obj, pl.DataType)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def is_pyarrow_chunked_array(ser: Any) -> TypeIs[pa.ChunkedArray[Any]]:
|
| 320 |
+
"""Check whether `ser` is a PyArrow ChunkedArray without importing PyArrow.
|
| 321 |
+
|
| 322 |
+
Warning:
|
| 323 |
+
This method cannot be called on Narwhals Series.
|
| 324 |
+
"""
|
| 325 |
+
_warn_if_narwhals_series(ser)
|
| 326 |
+
return (pa := get_pyarrow()) is not None and isinstance(ser, pa.ChunkedArray)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def is_pyarrow_table(df: Any) -> TypeIs[pa.Table]:
|
| 330 |
+
"""Check whether `df` is a PyArrow Table without importing PyArrow.
|
| 331 |
+
|
| 332 |
+
Warning:
|
| 333 |
+
This method cannot be called on Narwhals DataFrame/LazyFrame.
|
| 334 |
+
"""
|
| 335 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 336 |
+
return (pa := get_pyarrow()) is not None and isinstance(df, pa.Table)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def is_pyarrow_scalar(obj: Any) -> TypeIs[pa.Scalar[Any]]:
|
| 340 |
+
return (pa := get_pyarrow()) is not None and isinstance(obj, pa.Scalar)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def is_pyarrow_schema(obj: Any) -> TypeIs[pa.Schema]:
|
| 344 |
+
return bool(pa := get_pyarrow()) and isinstance(obj, pa.Schema)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def is_pyarrow_data_type(obj: Any) -> TypeIs[pa.DataType]:
|
| 348 |
+
return bool(pa := get_pyarrow()) and isinstance(obj, pa.DataType)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def is_pyspark_dataframe(df: Any) -> TypeIs[pyspark_sql.DataFrame]:
|
| 352 |
+
"""Check whether `df` is a PySpark DataFrame without importing PySpark.
|
| 353 |
+
|
| 354 |
+
Warning:
|
| 355 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 356 |
+
"""
|
| 357 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 358 |
+
return bool(
|
| 359 |
+
(pyspark_sql := get_pyspark_sql()) is not None
|
| 360 |
+
and isinstance(df, pyspark_sql.DataFrame)
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def is_pyspark_connect_dataframe(df: Any) -> TypeIs[PySparkConnectDataFrame]:
|
| 365 |
+
"""Check whether `df` is a PySpark Connect DataFrame without importing PySpark.
|
| 366 |
+
|
| 367 |
+
Warning:
|
| 368 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 369 |
+
"""
|
| 370 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 371 |
+
if get_pyspark_connect() is not None: # pragma: no cover
|
| 372 |
+
try:
|
| 373 |
+
from pyspark.sql.connect.dataframe import DataFrame
|
| 374 |
+
except ImportError:
|
| 375 |
+
return False
|
| 376 |
+
return isinstance(df, DataFrame)
|
| 377 |
+
return False
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def is_sqlframe_dataframe(df: Any) -> TypeIs[SQLFrameDataFrame]:
|
| 381 |
+
"""Check whether `df` is a SQLFrame DataFrame without importing SQLFrame.
|
| 382 |
+
|
| 383 |
+
Warning:
|
| 384 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 385 |
+
"""
|
| 386 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 387 |
+
if get_sqlframe() is not None:
|
| 388 |
+
from sqlframe.base.dataframe import BaseDataFrame
|
| 389 |
+
|
| 390 |
+
return isinstance(df, BaseDataFrame)
|
| 391 |
+
return False # pragma: no cover
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def is_numpy_array(arr: Any | _NDArray[_ShapeT]) -> TypeIs[_NDArray[_ShapeT]]:
|
| 395 |
+
"""Check whether `arr` is a NumPy Array without importing NumPy."""
|
| 396 |
+
return (np := get_numpy()) is not None and isinstance(arr, np.ndarray)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def is_numpy_array_1d(arr: Any) -> TypeIs[_1DArray]:
|
| 400 |
+
"""Check whether `arr` is a 1D NumPy Array without importing NumPy."""
|
| 401 |
+
return is_numpy_array(arr) and arr.ndim == 1
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def is_numpy_array_1d_int(arr: Any) -> TypeIs[_1DArrayInt]:
|
| 405 |
+
return (
|
| 406 |
+
(np := get_numpy())
|
| 407 |
+
and is_numpy_array_1d(arr)
|
| 408 |
+
and np.issubdtype(arr.dtype, np.integer)
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def is_numpy_array_1d_bool(arr: Any) -> TypeIs[_1DArrayInt]:
|
| 413 |
+
return (
|
| 414 |
+
(np := get_numpy())
|
| 415 |
+
and is_numpy_array_1d(arr)
|
| 416 |
+
and np.issubdtype(arr.dtype, np.bool_)
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def is_numpy_array_2d(arr: Any) -> TypeIs[_2DArray]:
|
| 421 |
+
"""Check whether `arr` is a 2D NumPy Array without importing NumPy."""
|
| 422 |
+
return is_numpy_array(arr) and arr.ndim == 2
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def is_numpy_scalar(scalar: Any) -> TypeGuard[_NumpyScalar]:
|
| 426 |
+
"""Check whether `scalar` is a NumPy Scalar without importing NumPy."""
|
| 427 |
+
# NOTE: Needs to stay as `TypeGuard`
|
| 428 |
+
# - Used in `Series.__getitem__`, but not annotated
|
| 429 |
+
# - `TypeGuard` is *hiding* that the check introduces an intersection
|
| 430 |
+
return (np := get_numpy()) is not None and isinstance(scalar, np.generic)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def is_pandas_like_dataframe(df: Any) -> bool:
|
| 434 |
+
"""Check whether `df` is a pandas-like DataFrame without doing any imports.
|
| 435 |
+
|
| 436 |
+
By "pandas-like", we mean: pandas, Modin, cuDF.
|
| 437 |
+
|
| 438 |
+
Warning:
|
| 439 |
+
This method cannot be called on a Narwhals DataFrame/LazyFrame.
|
| 440 |
+
"""
|
| 441 |
+
_warn_if_narwhals_df_or_lf(df)
|
| 442 |
+
return is_pandas_dataframe(df) or is_modin_dataframe(df) or is_cudf_dataframe(df)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def is_pandas_like_series(ser: Any) -> bool:
|
| 446 |
+
"""Check whether `ser` is a pandas-like Series without doing any imports.
|
| 447 |
+
|
| 448 |
+
By "pandas-like", we mean: pandas, Modin, cuDF.
|
| 449 |
+
|
| 450 |
+
Warning:
|
| 451 |
+
This method cannot be called on Narwhals Series.
|
| 452 |
+
"""
|
| 453 |
+
_warn_if_narwhals_series(ser)
|
| 454 |
+
return is_pandas_series(ser) or is_modin_series(ser) or is_cudf_series(ser)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def is_pandas_like_index(index: Any) -> bool:
|
| 458 |
+
"""Check whether `index` is a pandas-like Index without doing any imports.
|
| 459 |
+
|
| 460 |
+
By "pandas-like", we mean: pandas, Modin, cuDF.
|
| 461 |
+
"""
|
| 462 |
+
return (
|
| 463 |
+
is_pandas_index(index) or is_modin_index(index) or is_cudf_index(index)
|
| 464 |
+
) # pragma: no cover
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def is_pandas_like_dtype(obj: Any) -> TypeIs[PandasLikeDType]:
|
| 468 |
+
return bool(pd := get_pandas()) and isinstance(
|
| 469 |
+
obj, (pd.api.extensions.ExtensionDtype, get_numpy().dtype)
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def is_cudf_dtype(
|
| 474 |
+
obj: Any,
|
| 475 |
+
) -> TypeIs[pd.api.extensions.ExtensionDtype]: # pragma: no cover
|
| 476 |
+
return (
|
| 477 |
+
bool(pd := get_pandas())
|
| 478 |
+
and isinstance(obj, (pd.api.extensions.ExtensionDtype))
|
| 479 |
+
and hasattr(obj, "to_arrow")
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def is_into_series(native_series: Any | IntoSeriesT) -> TypeIs[IntoSeriesT]:
|
| 484 |
+
"""Check whether `native_series` can be converted to a Narwhals Series.
|
| 485 |
+
|
| 486 |
+
Arguments:
|
| 487 |
+
native_series: The object to check.
|
| 488 |
+
|
| 489 |
+
Examples:
|
| 490 |
+
>>> import pandas as pd
|
| 491 |
+
>>> import polars as pl
|
| 492 |
+
>>> import numpy as np
|
| 493 |
+
>>> import narwhals as nw
|
| 494 |
+
|
| 495 |
+
>>> s_pd = pd.Series([1, 2, 3])
|
| 496 |
+
>>> s_pl = pl.Series([1, 2, 3])
|
| 497 |
+
>>> np_arr = np.array([1, 2, 3])
|
| 498 |
+
|
| 499 |
+
>>> nw.dependencies.is_into_series(s_pd)
|
| 500 |
+
True
|
| 501 |
+
>>> nw.dependencies.is_into_series(s_pl)
|
| 502 |
+
True
|
| 503 |
+
>>> nw.dependencies.is_into_series(np_arr)
|
| 504 |
+
False
|
| 505 |
+
"""
|
| 506 |
+
from narwhals.series import Series
|
| 507 |
+
|
| 508 |
+
return (
|
| 509 |
+
isinstance(native_series, Series)
|
| 510 |
+
or hasattr(native_series, "__narwhals_series__")
|
| 511 |
+
or is_polars_series(native_series)
|
| 512 |
+
or is_pyarrow_chunked_array(native_series)
|
| 513 |
+
or is_pandas_like_series(native_series)
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def is_into_dataframe(native_dataframe: Any | IntoDataFrameT) -> TypeIs[IntoDataFrameT]:
|
| 518 |
+
"""Check whether `native_dataframe` can be converted to a Narwhals DataFrame.
|
| 519 |
+
|
| 520 |
+
Arguments:
|
| 521 |
+
native_dataframe: The object to check.
|
| 522 |
+
|
| 523 |
+
Examples:
|
| 524 |
+
>>> import pandas as pd
|
| 525 |
+
>>> import polars as pl
|
| 526 |
+
>>> import numpy as np
|
| 527 |
+
>>> from narwhals.dependencies import is_into_dataframe
|
| 528 |
+
|
| 529 |
+
>>> df_pd = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 530 |
+
>>> df_pl = pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
|
| 531 |
+
>>> np_arr = np.array([[1, 4], [2, 5], [3, 6]])
|
| 532 |
+
|
| 533 |
+
>>> is_into_dataframe(df_pd)
|
| 534 |
+
True
|
| 535 |
+
>>> is_into_dataframe(df_pl)
|
| 536 |
+
True
|
| 537 |
+
>>> is_into_dataframe(np_arr)
|
| 538 |
+
False
|
| 539 |
+
"""
|
| 540 |
+
from narwhals.dataframe import DataFrame
|
| 541 |
+
|
| 542 |
+
return (
|
| 543 |
+
isinstance(native_dataframe, DataFrame)
|
| 544 |
+
or hasattr(native_dataframe, "__narwhals_dataframe__")
|
| 545 |
+
or is_polars_dataframe(native_dataframe)
|
| 546 |
+
or is_pyarrow_table(native_dataframe)
|
| 547 |
+
or is_pandas_like_dataframe(native_dataframe)
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def is_narwhals_dataframe(
|
| 552 |
+
df: DataFrame[IntoDataFrameT] | Any,
|
| 553 |
+
) -> TypeIs[DataFrame[IntoDataFrameT]]:
|
| 554 |
+
"""Check whether `df` is a Narwhals DataFrame.
|
| 555 |
+
|
| 556 |
+
This is useful if you expect a user to pass in a Narwhals
|
| 557 |
+
DataFrame directly, and you want to catch both `narwhals.DataFrame`
|
| 558 |
+
and `narwhals.stable.v1.DataFrame`.
|
| 559 |
+
"""
|
| 560 |
+
from narwhals.dataframe import DataFrame
|
| 561 |
+
|
| 562 |
+
return isinstance(df, DataFrame)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def is_narwhals_lazyframe(
|
| 566 |
+
lf: Any | LazyFrame[IntoLazyFrameT],
|
| 567 |
+
) -> TypeIs[LazyFrame[IntoLazyFrameT]]:
|
| 568 |
+
"""Check whether `lf` is a Narwhals LazyFrame.
|
| 569 |
+
|
| 570 |
+
This is useful if you expect a user to pass in a Narwhals
|
| 571 |
+
LazyFrame directly, and you want to catch both `narwhals.LazyFrame`
|
| 572 |
+
and `narwhals.stable.v1.LazyFrame`.
|
| 573 |
+
"""
|
| 574 |
+
from narwhals.dataframe import LazyFrame
|
| 575 |
+
|
| 576 |
+
return isinstance(lf, LazyFrame)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def is_narwhals_series(ser: Any | Series[IntoSeriesT]) -> TypeIs[Series[IntoSeriesT]]:
|
| 580 |
+
"""Check whether `ser` is a Narwhals Series.
|
| 581 |
+
|
| 582 |
+
This is useful if you expect a user to pass in a Narwhals
|
| 583 |
+
Series directly, and you want to catch both `narwhals.Series`
|
| 584 |
+
and `narwhals.stable.v1.Series`.
|
| 585 |
+
"""
|
| 586 |
+
from narwhals.series import Series
|
| 587 |
+
|
| 588 |
+
return isinstance(ser, Series)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def is_narwhals_series_int(ser: Any | Series[IntoSeriesT]) -> TypeIs[Series[IntoSeriesT]]:
|
| 592 |
+
return is_narwhals_series(ser) and ser.dtype.is_integer()
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def is_narwhals_series_bool(
|
| 596 |
+
ser: Any | Series[IntoSeriesT],
|
| 597 |
+
) -> TypeIs[Series[IntoSeriesT]]:
|
| 598 |
+
return is_narwhals_series(ser) and ser.dtype.is_boolean()
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
__all__ = [
|
| 602 |
+
"get_cudf",
|
| 603 |
+
"get_ibis",
|
| 604 |
+
"get_modin",
|
| 605 |
+
"get_numpy",
|
| 606 |
+
"get_pandas",
|
| 607 |
+
"get_polars",
|
| 608 |
+
"get_pyarrow",
|
| 609 |
+
"is_cudf_dataframe",
|
| 610 |
+
"is_cudf_series",
|
| 611 |
+
"is_dask_dataframe",
|
| 612 |
+
"is_ibis_table",
|
| 613 |
+
"is_into_dataframe",
|
| 614 |
+
"is_into_series",
|
| 615 |
+
"is_modin_dataframe",
|
| 616 |
+
"is_modin_series",
|
| 617 |
+
"is_narwhals_dataframe",
|
| 618 |
+
"is_narwhals_lazyframe",
|
| 619 |
+
"is_narwhals_series",
|
| 620 |
+
"is_numpy_array",
|
| 621 |
+
"is_pandas_dataframe",
|
| 622 |
+
"is_pandas_index",
|
| 623 |
+
"is_pandas_like_dataframe",
|
| 624 |
+
"is_pandas_like_series",
|
| 625 |
+
"is_pandas_series",
|
| 626 |
+
"is_polars_dataframe",
|
| 627 |
+
"is_polars_lazyframe",
|
| 628 |
+
"is_polars_series",
|
| 629 |
+
"is_pyarrow_chunked_array",
|
| 630 |
+
"is_pyarrow_table",
|
| 631 |
+
]
|
.venv_haddock/lib/python3.12/site-packages/narwhals/dtypes.py
ADDED
|
@@ -0,0 +1,1042 @@
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import enum
|
| 4 |
+
from collections import OrderedDict
|
| 5 |
+
from collections.abc import Iterable, Mapping
|
| 6 |
+
from datetime import timezone
|
| 7 |
+
from itertools import starmap
|
| 8 |
+
from typing import TYPE_CHECKING
|
| 9 |
+
|
| 10 |
+
from narwhals._utils import (
|
| 11 |
+
_DeferredIterable,
|
| 12 |
+
isinstance_or_issubclass,
|
| 13 |
+
qualified_type_name,
|
| 14 |
+
)
|
| 15 |
+
from narwhals.exceptions import InvalidOperationError
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from collections.abc import Iterator, Sequence
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
import _typeshed
|
| 22 |
+
from typing_extensions import Self, TypeIs
|
| 23 |
+
|
| 24 |
+
from narwhals.typing import IntoDType, TimeUnit
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _validate_dtype(dtype: DType | type[DType]) -> None:
|
| 28 |
+
if not isinstance_or_issubclass(dtype, DType):
|
| 29 |
+
msg = (
|
| 30 |
+
f"Expected Narwhals dtype, got: {type(dtype)}.\n\n"
|
| 31 |
+
"Hint: if you were trying to cast to a type, use e.g. nw.Int64 instead of 'int64'."
|
| 32 |
+
)
|
| 33 |
+
raise TypeError(msg)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _is_into_dtype(obj: Any) -> TypeIs[IntoDType]:
|
| 37 |
+
return isinstance(obj, DType) or (
|
| 38 |
+
isinstance(obj, DTypeClass) and not issubclass(obj, NestedType)
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _is_nested_type(obj: Any) -> TypeIs[type[NestedType]]:
|
| 43 |
+
return isinstance(obj, DTypeClass) and issubclass(obj, NestedType)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _validate_into_dtype(dtype: Any) -> None:
|
| 47 |
+
if not _is_into_dtype(dtype):
|
| 48 |
+
if _is_nested_type(dtype):
|
| 49 |
+
name = f"nw.{dtype.__name__}"
|
| 50 |
+
msg = (
|
| 51 |
+
f"{name!r} is not valid in this context.\n\n"
|
| 52 |
+
f"Hint: instead of:\n\n"
|
| 53 |
+
f" {name}\n\n"
|
| 54 |
+
"use:\n\n"
|
| 55 |
+
f" {name}(...)"
|
| 56 |
+
)
|
| 57 |
+
else:
|
| 58 |
+
msg = f"Expected Narwhals dtype, got: {qualified_type_name(dtype)!r}."
|
| 59 |
+
raise TypeError(msg)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class DTypeClass(type):
|
| 63 |
+
"""Metaclass for DType classes.
|
| 64 |
+
|
| 65 |
+
- Nicely print classes.
|
| 66 |
+
- Ensure [`__slots__`] are always defined to prevent `__dict__` creation (empty by default).
|
| 67 |
+
|
| 68 |
+
[`__slots__`]: https://docs.python.org/3/reference/datamodel.html#object.__slots__
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
def __repr__(cls) -> str:
|
| 72 |
+
return cls.__name__
|
| 73 |
+
|
| 74 |
+
# https://github.com/python/typeshed/blob/776508741d76b58f9dcb2aaf42f7d4596a48d580/stdlib/abc.pyi#L13-L19
|
| 75 |
+
# https://github.com/python/typeshed/blob/776508741d76b58f9dcb2aaf42f7d4596a48d580/stdlib/_typeshed/__init__.pyi#L36-L40
|
| 76 |
+
# https://github.com/astral-sh/ruff/issues/8353#issuecomment-1786238311
|
| 77 |
+
# https://docs.python.org/3/reference/datamodel.html#creating-the-class-object
|
| 78 |
+
def __new__(
|
| 79 |
+
metacls: type[_typeshed.Self],
|
| 80 |
+
cls_name: str,
|
| 81 |
+
bases: tuple[type, ...],
|
| 82 |
+
namespace: dict[str, Any],
|
| 83 |
+
/,
|
| 84 |
+
**kwds: Any,
|
| 85 |
+
) -> _typeshed.Self:
|
| 86 |
+
namespace.setdefault("__slots__", ())
|
| 87 |
+
return super().__new__(metacls, cls_name, bases, namespace, **kwds) # type: ignore[no-any-return, misc]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class DType(metaclass=DTypeClass):
|
| 91 |
+
"""Base class for all Narwhals data types."""
|
| 92 |
+
|
| 93 |
+
__slots__ = () # NOTE: Keep this one defined manually for the type checker
|
| 94 |
+
|
| 95 |
+
def __repr__(self) -> str:
|
| 96 |
+
return self.__class__.__qualname__
|
| 97 |
+
|
| 98 |
+
@classmethod
|
| 99 |
+
def base_type(cls) -> type[Self]:
|
| 100 |
+
"""Return this DType's fundamental/root type class.
|
| 101 |
+
|
| 102 |
+
Examples:
|
| 103 |
+
>>> import narwhals as nw
|
| 104 |
+
>>> nw.Datetime("us").base_type()
|
| 105 |
+
Datetime
|
| 106 |
+
>>> nw.String.base_type()
|
| 107 |
+
String
|
| 108 |
+
>>> nw.List(nw.Int64).base_type()
|
| 109 |
+
List
|
| 110 |
+
"""
|
| 111 |
+
return cls
|
| 112 |
+
|
| 113 |
+
@classmethod
|
| 114 |
+
def is_numeric(cls: type[Self]) -> bool:
|
| 115 |
+
"""Check whether the data type is a numeric type."""
|
| 116 |
+
return issubclass(cls, NumericType)
|
| 117 |
+
|
| 118 |
+
@classmethod
|
| 119 |
+
def is_integer(cls: type[Self]) -> bool:
|
| 120 |
+
"""Check whether the data type is an integer type."""
|
| 121 |
+
return issubclass(cls, IntegerType)
|
| 122 |
+
|
| 123 |
+
@classmethod
|
| 124 |
+
def is_signed_integer(cls: type[Self]) -> bool:
|
| 125 |
+
"""Check whether the data type is a signed integer type."""
|
| 126 |
+
return issubclass(cls, SignedIntegerType)
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def is_unsigned_integer(cls: type[Self]) -> bool:
|
| 130 |
+
"""Check whether the data type is an unsigned integer type."""
|
| 131 |
+
return issubclass(cls, UnsignedIntegerType)
|
| 132 |
+
|
| 133 |
+
@classmethod
|
| 134 |
+
def is_float(cls: type[Self]) -> bool:
|
| 135 |
+
"""Check whether the data type is a floating point type."""
|
| 136 |
+
return issubclass(cls, FloatType)
|
| 137 |
+
|
| 138 |
+
@classmethod
|
| 139 |
+
def is_decimal(cls: type[Self]) -> bool:
|
| 140 |
+
"""Check whether the data type is a decimal type."""
|
| 141 |
+
return issubclass(cls, Decimal)
|
| 142 |
+
|
| 143 |
+
@classmethod
|
| 144 |
+
def is_temporal(cls: type[Self]) -> bool:
|
| 145 |
+
"""Check whether the data type is a temporal type."""
|
| 146 |
+
return issubclass(cls, TemporalType)
|
| 147 |
+
|
| 148 |
+
@classmethod
|
| 149 |
+
def is_nested(cls: type[Self]) -> bool:
|
| 150 |
+
"""Check whether the data type is a nested type."""
|
| 151 |
+
return issubclass(cls, NestedType)
|
| 152 |
+
|
| 153 |
+
@classmethod
|
| 154 |
+
def is_boolean(cls: type[Self]) -> bool:
|
| 155 |
+
"""Check whether the data type is a boolean type."""
|
| 156 |
+
return issubclass(cls, Boolean)
|
| 157 |
+
|
| 158 |
+
def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override]
|
| 159 |
+
"""Check if this DType is equivalent to another DType.
|
| 160 |
+
|
| 161 |
+
Examples:
|
| 162 |
+
>>> import narwhals as nw
|
| 163 |
+
>>> nw.String() == nw.String()
|
| 164 |
+
True
|
| 165 |
+
>>> nw.String() == nw.String
|
| 166 |
+
True
|
| 167 |
+
>>> nw.Int16() == nw.Int32
|
| 168 |
+
False
|
| 169 |
+
>>> nw.Boolean() == nw.Int8
|
| 170 |
+
False
|
| 171 |
+
>>> nw.Date() == nw.Datetime
|
| 172 |
+
False
|
| 173 |
+
"""
|
| 174 |
+
return isinstance_or_issubclass(other, type(self))
|
| 175 |
+
|
| 176 |
+
def __hash__(self) -> int:
|
| 177 |
+
return hash(self.__class__)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class NumericType(DType):
|
| 181 |
+
"""Base class for numeric data types."""
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class IntegerType(NumericType):
|
| 185 |
+
"""Base class for integer data types."""
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class SignedIntegerType(IntegerType):
|
| 189 |
+
"""Base class for signed integer data types."""
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class UnsignedIntegerType(IntegerType):
|
| 193 |
+
"""Base class for unsigned integer data types."""
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class FloatType(NumericType):
|
| 197 |
+
"""Base class for float data types."""
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class TemporalType(DType):
|
| 201 |
+
"""Base class for temporal data types."""
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class NestedType(DType):
|
| 205 |
+
"""Base class for nested data types."""
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class Decimal(NumericType):
|
| 209 |
+
"""Decimal 128-bit type with an optional precision and non-negative scale.
|
| 210 |
+
|
| 211 |
+
Arguments:
|
| 212 |
+
precision: Maximum number of digits in each number. If set to `None` (default),
|
| 213 |
+
the precision is set to 38 (the maximum supported by Polars).
|
| 214 |
+
scale: Number of digits to the right of the decimal point in each number.
|
| 215 |
+
|
| 216 |
+
Examples:
|
| 217 |
+
>>> import polars as pl
|
| 218 |
+
>>> import narwhals as nw
|
| 219 |
+
>>> s = pl.Series(["1.5"], dtype=pl.Decimal)
|
| 220 |
+
>>> nw.from_native(s, series_only=True).dtype
|
| 221 |
+
Decimal(precision=2, scale=1)
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
__slots__ = ("precision", "scale")
|
| 225 |
+
|
| 226 |
+
precision: int
|
| 227 |
+
scale: int
|
| 228 |
+
|
| 229 |
+
# !NOTE: Reason for `precision: int | None = None` rather than `precision: int = 38`
|
| 230 |
+
# is to mirror polars signature https://github.com/pola-rs/polars/blob/bb79993c3aa91d0db7d20be8f75c8075cad97067/py-polars/src/polars/datatypes/classes.py#L450-L454
|
| 231 |
+
def __init__(self, precision: int | None = None, scale: int = 0) -> None:
|
| 232 |
+
precision = 38 if precision is None else precision
|
| 233 |
+
|
| 234 |
+
if not ((is_int := isinstance(precision, int)) and 0 <= precision <= 38):
|
| 235 |
+
msg = f"precision must be a positive integer between 0 and 38, found {precision!r}"
|
| 236 |
+
raise ValueError(msg) if is_int else TypeError(msg)
|
| 237 |
+
|
| 238 |
+
if not ((is_int := isinstance(scale, int)) and scale >= 0):
|
| 239 |
+
msg = f"scale must be a positive integer, found {scale!r}"
|
| 240 |
+
raise ValueError(msg) if is_int else TypeError(msg)
|
| 241 |
+
|
| 242 |
+
if scale > precision:
|
| 243 |
+
msg = "scale must be less than or equal to precision"
|
| 244 |
+
raise InvalidOperationError(msg)
|
| 245 |
+
|
| 246 |
+
self.precision = precision
|
| 247 |
+
self.scale = scale
|
| 248 |
+
|
| 249 |
+
def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override]
|
| 250 |
+
return (other is Decimal) or (
|
| 251 |
+
isinstance(other, self.__class__)
|
| 252 |
+
and self.precision == other.precision
|
| 253 |
+
and self.scale == other.scale
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
def __hash__(self) -> int: # pragma: no cover
|
| 257 |
+
return hash((self.__class__, self.precision, self.scale))
|
| 258 |
+
|
| 259 |
+
def __repr__(self) -> str: # pragma: no cover
|
| 260 |
+
class_name = self.__class__.__name__
|
| 261 |
+
return f"{class_name}(precision={self.precision!r}, scale={self.scale!r})"
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class Int128(SignedIntegerType):
|
| 265 |
+
"""128-bit signed integer type.
|
| 266 |
+
|
| 267 |
+
Examples:
|
| 268 |
+
>>> import polars as pl
|
| 269 |
+
>>> import pyarrow as pa
|
| 270 |
+
>>> import narwhals as nw
|
| 271 |
+
>>> import duckdb
|
| 272 |
+
>>> s_native = pl.Series([2, 1, 3, 7])
|
| 273 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 274 |
+
>>> df_native = pa.table({"a": [2, 1, 3, 7]})
|
| 275 |
+
>>> rel = duckdb.sql(" SELECT CAST (a AS INT128) AS a FROM df_native ")
|
| 276 |
+
|
| 277 |
+
>>> s.cast(nw.Int128).dtype
|
| 278 |
+
Int128
|
| 279 |
+
>>> nw.from_native(rel).collect_schema()["a"]
|
| 280 |
+
Int128
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class Int64(SignedIntegerType):
|
| 285 |
+
"""64-bit signed integer type.
|
| 286 |
+
|
| 287 |
+
Examples:
|
| 288 |
+
>>> import polars as pl
|
| 289 |
+
>>> import narwhals as nw
|
| 290 |
+
>>> s_native = pl.Series([2, 1, 3, 7])
|
| 291 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 292 |
+
>>> s.cast(nw.Int64).dtype
|
| 293 |
+
Int64
|
| 294 |
+
"""
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class Int32(SignedIntegerType):
|
| 298 |
+
"""32-bit signed integer type.
|
| 299 |
+
|
| 300 |
+
Examples:
|
| 301 |
+
>>> import pyarrow as pa
|
| 302 |
+
>>> import narwhals as nw
|
| 303 |
+
>>> s_native = pa.chunked_array([[2, 1, 3, 7]])
|
| 304 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 305 |
+
>>> s.cast(nw.Int32).dtype
|
| 306 |
+
Int32
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
class Int16(SignedIntegerType):
|
| 311 |
+
"""16-bit signed integer type.
|
| 312 |
+
|
| 313 |
+
Examples:
|
| 314 |
+
>>> import polars as pl
|
| 315 |
+
>>> import narwhals as nw
|
| 316 |
+
>>> s_native = pl.Series([2, 1, 3, 7])
|
| 317 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 318 |
+
>>> s.cast(nw.Int16).dtype
|
| 319 |
+
Int16
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class Int8(SignedIntegerType):
|
| 324 |
+
"""8-bit signed integer type.
|
| 325 |
+
|
| 326 |
+
Examples:
|
| 327 |
+
>>> import pandas as pd
|
| 328 |
+
>>> import narwhals as nw
|
| 329 |
+
>>> s_native = pd.Series([2, 1, 3, 7])
|
| 330 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 331 |
+
>>> s.cast(nw.Int8).dtype
|
| 332 |
+
Int8
|
| 333 |
+
"""
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
class UInt128(UnsignedIntegerType):
|
| 337 |
+
"""128-bit unsigned integer type.
|
| 338 |
+
|
| 339 |
+
Examples:
|
| 340 |
+
>>> import pandas as pd
|
| 341 |
+
>>> import narwhals as nw
|
| 342 |
+
>>> import duckdb
|
| 343 |
+
>>> df_native = pd.DataFrame({"a": [2, 1, 3, 7]})
|
| 344 |
+
>>> rel = duckdb.sql(" SELECT CAST (a AS UINT128) AS a FROM df_native ")
|
| 345 |
+
>>> nw.from_native(rel).collect_schema()["a"]
|
| 346 |
+
UInt128
|
| 347 |
+
"""
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
class UInt64(UnsignedIntegerType):
|
| 351 |
+
"""64-bit unsigned integer type.
|
| 352 |
+
|
| 353 |
+
Examples:
|
| 354 |
+
>>> import pandas as pd
|
| 355 |
+
>>> import narwhals as nw
|
| 356 |
+
>>> s_native = pd.Series([2, 1, 3, 7])
|
| 357 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 358 |
+
>>> s.cast(nw.UInt64).dtype
|
| 359 |
+
UInt64
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class UInt32(UnsignedIntegerType):
|
| 364 |
+
"""32-bit unsigned integer type.
|
| 365 |
+
|
| 366 |
+
Examples:
|
| 367 |
+
>>> import polars as pl
|
| 368 |
+
>>> import narwhals as nw
|
| 369 |
+
>>> s_native = pl.Series([2, 1, 3, 7])
|
| 370 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 371 |
+
>>> s.cast(nw.UInt32).dtype
|
| 372 |
+
UInt32
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
class UInt16(UnsignedIntegerType):
|
| 377 |
+
"""16-bit unsigned integer type.
|
| 378 |
+
|
| 379 |
+
Examples:
|
| 380 |
+
>>> import polars as pl
|
| 381 |
+
>>> import narwhals as nw
|
| 382 |
+
>>> s_native = pl.Series([2, 1, 3, 7])
|
| 383 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 384 |
+
>>> s.cast(nw.UInt16).dtype
|
| 385 |
+
UInt16
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class UInt8(UnsignedIntegerType):
|
| 390 |
+
"""8-bit unsigned integer type.
|
| 391 |
+
|
| 392 |
+
Examples:
|
| 393 |
+
>>> import polars as pl
|
| 394 |
+
>>> import narwhals as nw
|
| 395 |
+
>>> s_native = pl.Series([2, 1, 3, 7])
|
| 396 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 397 |
+
>>> s.cast(nw.UInt8).dtype
|
| 398 |
+
UInt8
|
| 399 |
+
"""
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
class Float64(FloatType):
|
| 403 |
+
"""64-bit floating point type.
|
| 404 |
+
|
| 405 |
+
Examples:
|
| 406 |
+
>>> import pyarrow as pa
|
| 407 |
+
>>> import narwhals as nw
|
| 408 |
+
>>> s_native = pa.chunked_array([[0.001, 0.1, 0.01, 0.1]])
|
| 409 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 410 |
+
>>> s.cast(nw.Float64).dtype
|
| 411 |
+
Float64
|
| 412 |
+
"""
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class Float32(FloatType):
|
| 416 |
+
"""32-bit floating point type.
|
| 417 |
+
|
| 418 |
+
Examples:
|
| 419 |
+
>>> import polars as pl
|
| 420 |
+
>>> import narwhals as nw
|
| 421 |
+
>>> s_native = pl.Series([0.001, 0.1, 0.01, 0.1])
|
| 422 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 423 |
+
>>> s.cast(nw.Float32).dtype
|
| 424 |
+
Float32
|
| 425 |
+
"""
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class String(DType):
|
| 429 |
+
"""UTF-8 encoded string type.
|
| 430 |
+
|
| 431 |
+
Examples:
|
| 432 |
+
>>> import pandas as pd
|
| 433 |
+
>>> import narwhals as nw
|
| 434 |
+
>>> s_native = pd.Series(["beluga", "narwhal", "orca", "vaquita"])
|
| 435 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 436 |
+
String
|
| 437 |
+
"""
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
class Boolean(DType):
|
| 441 |
+
"""Boolean type.
|
| 442 |
+
|
| 443 |
+
Examples:
|
| 444 |
+
>>> import pyarrow as pa
|
| 445 |
+
>>> import narwhals as nw
|
| 446 |
+
>>> s_native = pa.chunked_array([[True, False, False, True]])
|
| 447 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 448 |
+
Boolean
|
| 449 |
+
"""
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
class Object(DType):
|
| 453 |
+
"""Data type for wrapping arbitrary Python objects.
|
| 454 |
+
|
| 455 |
+
Examples:
|
| 456 |
+
>>> import pandas as pd
|
| 457 |
+
>>> import narwhals as nw
|
| 458 |
+
>>> class Foo: ...
|
| 459 |
+
>>> s_native = pd.Series([Foo(), Foo()])
|
| 460 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 461 |
+
Object
|
| 462 |
+
"""
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
class Unknown(DType):
|
| 466 |
+
"""Type representing DataType values that could not be determined statically.
|
| 467 |
+
|
| 468 |
+
Examples:
|
| 469 |
+
>>> import pandas as pd
|
| 470 |
+
>>> import narwhals as nw
|
| 471 |
+
>>> s_native = pd.Series(pd.period_range("2000-01", periods=4, freq="M"))
|
| 472 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 473 |
+
Unknown
|
| 474 |
+
"""
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
class _DatetimeMeta(DTypeClass):
|
| 478 |
+
@property
|
| 479 |
+
def time_unit(cls) -> TimeUnit:
|
| 480 |
+
"""Unit of time. Defaults to `'us'` (microseconds)."""
|
| 481 |
+
return "us"
|
| 482 |
+
|
| 483 |
+
@property
|
| 484 |
+
def time_zone(cls) -> str | None:
|
| 485 |
+
"""Time zone string. Defaults to `None`."""
|
| 486 |
+
return None
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
class Datetime(TemporalType, metaclass=_DatetimeMeta):
|
| 490 |
+
"""Data type representing a calendar date and time of day.
|
| 491 |
+
|
| 492 |
+
Arguments:
|
| 493 |
+
time_unit: Unit of time. Defaults to `'us'` (microseconds).
|
| 494 |
+
time_zone: Time zone string, as defined in zoneinfo (to see valid strings run
|
| 495 |
+
`import zoneinfo; zoneinfo.available_timezones()` for a full list).
|
| 496 |
+
|
| 497 |
+
Notes:
|
| 498 |
+
Adapted from [Polars implementation](https://github.com/pola-rs/polars/blob/py-1.7.1/py-polars/polars/datatypes/classes.py#L398-L457)
|
| 499 |
+
|
| 500 |
+
Examples:
|
| 501 |
+
>>> from datetime import datetime, timedelta
|
| 502 |
+
>>> import polars as pl
|
| 503 |
+
>>> import narwhals as nw
|
| 504 |
+
>>> s_native = (
|
| 505 |
+
... pl.Series([datetime(2024, 12, 9) + timedelta(days=n) for n in range(5)])
|
| 506 |
+
... .cast(pl.Datetime("ms"))
|
| 507 |
+
... .dt.replace_time_zone("Africa/Accra")
|
| 508 |
+
... )
|
| 509 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 510 |
+
Datetime(time_unit='ms', time_zone='Africa/Accra')
|
| 511 |
+
"""
|
| 512 |
+
|
| 513 |
+
__slots__ = ("time_unit", "time_zone")
|
| 514 |
+
|
| 515 |
+
def __init__(
|
| 516 |
+
self, time_unit: TimeUnit = "us", time_zone: str | timezone | None = None
|
| 517 |
+
) -> None:
|
| 518 |
+
if time_unit not in {"s", "ms", "us", "ns"}:
|
| 519 |
+
msg = (
|
| 520 |
+
"invalid `time_unit`"
|
| 521 |
+
f"\n\nExpected one of {{'ns','us','ms', 's'}}, got {time_unit!r}."
|
| 522 |
+
)
|
| 523 |
+
raise ValueError(msg)
|
| 524 |
+
|
| 525 |
+
if isinstance(time_zone, timezone):
|
| 526 |
+
time_zone = str(time_zone)
|
| 527 |
+
|
| 528 |
+
self.time_unit: TimeUnit = time_unit
|
| 529 |
+
"""Unit of time."""
|
| 530 |
+
self.time_zone: str | None = time_zone
|
| 531 |
+
"""Time zone string, as defined in zoneinfo.
|
| 532 |
+
|
| 533 |
+
Notes:
|
| 534 |
+
To see valid strings run `import zoneinfo; zoneinfo.available_timezones()` for a full list.
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override]
|
| 538 |
+
"""Check if this Datetime is equivalent to another DType.
|
| 539 |
+
|
| 540 |
+
Examples:
|
| 541 |
+
>>> import narwhals as nw
|
| 542 |
+
>>> nw.Datetime("s") == nw.Datetime("s")
|
| 543 |
+
True
|
| 544 |
+
>>> nw.Datetime() == nw.Datetime("us")
|
| 545 |
+
True
|
| 546 |
+
>>> nw.Datetime("us") == nw.Datetime("ns")
|
| 547 |
+
False
|
| 548 |
+
>>> nw.Datetime("us", "UTC") == nw.Datetime(time_unit="us", time_zone="UTC")
|
| 549 |
+
True
|
| 550 |
+
>>> nw.Datetime(time_zone="UTC") == nw.Datetime(time_zone="EST")
|
| 551 |
+
False
|
| 552 |
+
>>> nw.Datetime() == nw.Duration()
|
| 553 |
+
False
|
| 554 |
+
>>> nw.Datetime("ms") == nw.Datetime
|
| 555 |
+
True
|
| 556 |
+
"""
|
| 557 |
+
if type(other) is _DatetimeMeta:
|
| 558 |
+
return True
|
| 559 |
+
if isinstance(other, self.__class__):
|
| 560 |
+
return self.time_unit == other.time_unit and self.time_zone == other.time_zone
|
| 561 |
+
return False # pragma: no cover
|
| 562 |
+
|
| 563 |
+
def __hash__(self) -> int: # pragma: no cover
|
| 564 |
+
return hash((self.__class__, self.time_unit, self.time_zone))
|
| 565 |
+
|
| 566 |
+
def __repr__(self) -> str: # pragma: no cover
|
| 567 |
+
class_name = self.__class__.__name__
|
| 568 |
+
return f"{class_name}(time_unit={self.time_unit!r}, time_zone={self.time_zone!r})"
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
class _DurationMeta(DTypeClass):
|
| 572 |
+
@property
|
| 573 |
+
def time_unit(cls) -> TimeUnit:
|
| 574 |
+
"""Unit of time. Defaults to `'us'` (microseconds)."""
|
| 575 |
+
return "us"
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
class Duration(TemporalType, metaclass=_DurationMeta):
|
| 579 |
+
"""Data type representing a time duration.
|
| 580 |
+
|
| 581 |
+
Arguments:
|
| 582 |
+
time_unit: Unit of time. Defaults to `'us'` (microseconds).
|
| 583 |
+
|
| 584 |
+
Notes:
|
| 585 |
+
Adapted from [Polars implementation](https://github.com/pola-rs/polars/blob/py-1.7.1/py-polars/polars/datatypes/classes.py#L460-L502)
|
| 586 |
+
|
| 587 |
+
Examples:
|
| 588 |
+
>>> from datetime import timedelta
|
| 589 |
+
>>> import pyarrow as pa
|
| 590 |
+
>>> import narwhals as nw
|
| 591 |
+
>>> s_native = pa.chunked_array(
|
| 592 |
+
... [[timedelta(seconds=d) for d in range(1, 4)]], type=pa.duration("ms")
|
| 593 |
+
... )
|
| 594 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 595 |
+
Duration(time_unit='ms')
|
| 596 |
+
"""
|
| 597 |
+
|
| 598 |
+
__slots__ = ("time_unit",)
|
| 599 |
+
|
| 600 |
+
def __init__(self, time_unit: TimeUnit = "us") -> None:
|
| 601 |
+
if time_unit not in {"s", "ms", "us", "ns"}:
|
| 602 |
+
msg = (
|
| 603 |
+
"invalid `time_unit`"
|
| 604 |
+
f"\n\nExpected one of {{'ns','us','ms', 's'}}, got {time_unit!r}."
|
| 605 |
+
)
|
| 606 |
+
raise ValueError(msg)
|
| 607 |
+
|
| 608 |
+
self.time_unit: TimeUnit = time_unit
|
| 609 |
+
"""Unit of time."""
|
| 610 |
+
|
| 611 |
+
def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override]
|
| 612 |
+
"""Check if this Duration is equivalent to another DType.
|
| 613 |
+
|
| 614 |
+
Examples:
|
| 615 |
+
>>> import narwhals as nw
|
| 616 |
+
>>> nw.Duration("us") == nw.Duration("us")
|
| 617 |
+
True
|
| 618 |
+
>>> nw.Duration() == nw.Duration("us")
|
| 619 |
+
True
|
| 620 |
+
>>> nw.Duration("us") == nw.Duration("ns")
|
| 621 |
+
False
|
| 622 |
+
>>> nw.Duration() == nw.Datetime()
|
| 623 |
+
False
|
| 624 |
+
>>> nw.Duration("ms") == nw.Duration
|
| 625 |
+
True
|
| 626 |
+
"""
|
| 627 |
+
if type(other) is _DurationMeta:
|
| 628 |
+
return True
|
| 629 |
+
if isinstance(other, self.__class__):
|
| 630 |
+
return self.time_unit == other.time_unit
|
| 631 |
+
return False # pragma: no cover
|
| 632 |
+
|
| 633 |
+
def __hash__(self) -> int: # pragma: no cover
|
| 634 |
+
return hash((self.__class__, self.time_unit))
|
| 635 |
+
|
| 636 |
+
def __repr__(self) -> str: # pragma: no cover
|
| 637 |
+
class_name = self.__class__.__name__
|
| 638 |
+
return f"{class_name}(time_unit={self.time_unit!r})"
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
class Categorical(DType):
|
| 642 |
+
"""A categorical encoding of a set of strings.
|
| 643 |
+
|
| 644 |
+
Examples:
|
| 645 |
+
>>> import polars as pl
|
| 646 |
+
>>> import narwhals as nw
|
| 647 |
+
>>> s_native = pl.Series(["beluga", "narwhal", "orca"])
|
| 648 |
+
>>> nw.from_native(s_native, series_only=True).cast(nw.Categorical).dtype
|
| 649 |
+
Categorical
|
| 650 |
+
"""
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class Enum(DType):
|
| 654 |
+
"""A fixed categorical encoding of a unique set of strings.
|
| 655 |
+
|
| 656 |
+
Polars has an Enum data type. In pandas, ordered categories get mapped
|
| 657 |
+
to Enum. PyArrow has no Enum equivalent.
|
| 658 |
+
|
| 659 |
+
Examples:
|
| 660 |
+
>>> import narwhals as nw
|
| 661 |
+
>>> nw.Enum(["beluga", "narwhal", "orca"])
|
| 662 |
+
Enum(categories=['beluga', 'narwhal', 'orca'])
|
| 663 |
+
"""
|
| 664 |
+
|
| 665 |
+
__slots__ = ("_cached_categories", "_delayed_categories")
|
| 666 |
+
|
| 667 |
+
def __init__(self, categories: Iterable[str] | type[enum.Enum]) -> None:
|
| 668 |
+
self._delayed_categories: _DeferredIterable[str] | None = None
|
| 669 |
+
self._cached_categories: tuple[str, ...] | None = None
|
| 670 |
+
|
| 671 |
+
if isinstance(categories, _DeferredIterable):
|
| 672 |
+
self._delayed_categories = categories
|
| 673 |
+
elif isinstance(categories, type) and issubclass(categories, enum.Enum):
|
| 674 |
+
self._cached_categories = tuple(member.value for member in categories)
|
| 675 |
+
else:
|
| 676 |
+
self._cached_categories = tuple(categories)
|
| 677 |
+
|
| 678 |
+
@property
|
| 679 |
+
def categories(self) -> tuple[str, ...]:
|
| 680 |
+
"""The categories in the dataset."""
|
| 681 |
+
if (cached := self._cached_categories) is not None:
|
| 682 |
+
return cached
|
| 683 |
+
if (delayed := self._delayed_categories) is not None:
|
| 684 |
+
self._cached_categories = delayed.to_tuple()
|
| 685 |
+
return self._cached_categories
|
| 686 |
+
msg = f"Internal structure of {type(self).__name__!r} is invalid." # pragma: no cover
|
| 687 |
+
raise TypeError(msg) # pragma: no cover
|
| 688 |
+
|
| 689 |
+
def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override]
|
| 690 |
+
"""Check if this Enum is equivalent to another DType.
|
| 691 |
+
|
| 692 |
+
Examples:
|
| 693 |
+
>>> import narwhals as nw
|
| 694 |
+
>>> nw.Enum(["a", "b", "c"]) == nw.Enum(["a", "b", "c"])
|
| 695 |
+
True
|
| 696 |
+
>>> import polars as pl
|
| 697 |
+
>>> categories = pl.Series(["a", "b", "c"])
|
| 698 |
+
>>> nw.Enum(["a", "b", "c"]) == nw.Enum(categories)
|
| 699 |
+
True
|
| 700 |
+
>>> nw.Enum(["a", "b", "c"]) == nw.Enum(["b", "a", "c"])
|
| 701 |
+
False
|
| 702 |
+
>>> nw.Enum(["a", "b", "c"]) == nw.Enum(["a"])
|
| 703 |
+
False
|
| 704 |
+
>>> nw.Enum(["a", "b", "c"]) == nw.Categorical
|
| 705 |
+
False
|
| 706 |
+
>>> nw.Enum(["a", "b", "c"]) == nw.Enum
|
| 707 |
+
True
|
| 708 |
+
"""
|
| 709 |
+
if type(other) is DTypeClass:
|
| 710 |
+
return other is Enum
|
| 711 |
+
return isinstance(other, type(self)) and self.categories == other.categories
|
| 712 |
+
|
| 713 |
+
def __hash__(self) -> int:
|
| 714 |
+
return hash((self.__class__, tuple(self.categories)))
|
| 715 |
+
|
| 716 |
+
def __repr__(self) -> str:
|
| 717 |
+
return f"{type(self).__name__}(categories={list(self.categories)!r})"
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
class Field:
|
| 721 |
+
"""Definition of a single field within a `Struct` DType.
|
| 722 |
+
|
| 723 |
+
Arguments:
|
| 724 |
+
name: The name of the field within its parent `Struct`.
|
| 725 |
+
dtype: The `DType` of the field's values.
|
| 726 |
+
|
| 727 |
+
Examples:
|
| 728 |
+
>>> import pyarrow as pa
|
| 729 |
+
>>> import narwhals as nw
|
| 730 |
+
>>> data = [{"a": 1, "b": ["narwhal", "beluga"]}, {"a": 2, "b": ["orca"]}]
|
| 731 |
+
>>> ser_pa = pa.chunked_array([data])
|
| 732 |
+
>>> nw.from_native(ser_pa, series_only=True).dtype.fields
|
| 733 |
+
[Field('a', Int64), Field('b', List(String))]
|
| 734 |
+
"""
|
| 735 |
+
|
| 736 |
+
__slots__ = ("dtype", "name")
|
| 737 |
+
name: str
|
| 738 |
+
"""The name of the field within its parent `Struct`."""
|
| 739 |
+
dtype: IntoDType
|
| 740 |
+
"""The `DType` of the field's values."""
|
| 741 |
+
|
| 742 |
+
def __init__(self, name: str, dtype: IntoDType) -> None:
|
| 743 |
+
self.name = name
|
| 744 |
+
self.dtype = dtype
|
| 745 |
+
|
| 746 |
+
def __eq__(self, other: Field) -> bool: # type: ignore[override]
|
| 747 |
+
"""Check if this Field is equivalent to another Field.
|
| 748 |
+
|
| 749 |
+
Two fields are equivalent if they have the same name and the same dtype.
|
| 750 |
+
|
| 751 |
+
Examples:
|
| 752 |
+
>>> import narwhals as nw
|
| 753 |
+
>>> nw.Field("a", nw.String) == nw.Field("a", nw.String())
|
| 754 |
+
True
|
| 755 |
+
>>> nw.Field("a", nw.String) == nw.Field("a", nw.String)
|
| 756 |
+
True
|
| 757 |
+
>>> nw.Field("a", nw.String) == nw.Field("a", nw.Datetime)
|
| 758 |
+
False
|
| 759 |
+
>>> nw.Field("a", nw.String) == nw.Field("b", nw.String)
|
| 760 |
+
False
|
| 761 |
+
>>> nw.Field("a", nw.String) == nw.String
|
| 762 |
+
False
|
| 763 |
+
"""
|
| 764 |
+
return (
|
| 765 |
+
isinstance(other, Field)
|
| 766 |
+
and (self.name == other.name)
|
| 767 |
+
and (self.dtype == other.dtype)
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
def __hash__(self) -> int:
|
| 771 |
+
return hash((self.name, self.dtype))
|
| 772 |
+
|
| 773 |
+
def __repr__(self) -> str:
|
| 774 |
+
class_name = self.__class__.__name__
|
| 775 |
+
return f"{class_name}({self.name!r}, {self.dtype})"
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
class Struct(NestedType):
|
| 779 |
+
"""Struct composite type.
|
| 780 |
+
|
| 781 |
+
Arguments:
|
| 782 |
+
fields: The fields that make up the struct. Can be either a sequence of Field
|
| 783 |
+
objects or a mapping of column names to data types.
|
| 784 |
+
|
| 785 |
+
Examples:
|
| 786 |
+
>>> import pyarrow as pa
|
| 787 |
+
>>> import narwhals as nw
|
| 788 |
+
>>> s_native = pa.chunked_array(
|
| 789 |
+
... [[{"a": 1, "b": ["narwhal", "beluga"]}, {"a": 2, "b": ["orca"]}]]
|
| 790 |
+
... )
|
| 791 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 792 |
+
Struct({'a': Int64, 'b': List(String)})
|
| 793 |
+
"""
|
| 794 |
+
|
| 795 |
+
__slots__ = ("fields",)
|
| 796 |
+
fields: list[Field]
|
| 797 |
+
"""The fields that make up the struct."""
|
| 798 |
+
|
| 799 |
+
def __init__(self, fields: Sequence[Field] | Mapping[str, IntoDType]) -> None:
|
| 800 |
+
if isinstance(fields, Mapping):
|
| 801 |
+
self.fields = list(starmap(Field, fields.items()))
|
| 802 |
+
else:
|
| 803 |
+
self.fields = list(fields)
|
| 804 |
+
|
| 805 |
+
def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override]
|
| 806 |
+
"""Check if this Struct is equivalent to another DType.
|
| 807 |
+
|
| 808 |
+
Examples:
|
| 809 |
+
>>> import narwhals as nw
|
| 810 |
+
>>> nw.Struct({"a": nw.Int64}) == nw.Struct({"a": nw.Int64})
|
| 811 |
+
True
|
| 812 |
+
>>> nw.Struct({"a": nw.Int64}) == nw.Struct({"a": nw.Boolean})
|
| 813 |
+
False
|
| 814 |
+
>>> nw.Struct({"a": nw.Int64}) == nw.Struct({"b": nw.Int64})
|
| 815 |
+
False
|
| 816 |
+
>>> nw.Struct({"a": nw.Int64}) == nw.Struct([nw.Field("a", nw.Int64)])
|
| 817 |
+
True
|
| 818 |
+
|
| 819 |
+
If a parent type is not specific about its inner type, we infer it as equal
|
| 820 |
+
|
| 821 |
+
>>> nw.Struct({"a": nw.Int64}) == nw.Struct
|
| 822 |
+
True
|
| 823 |
+
"""
|
| 824 |
+
if type(other) is DTypeClass and issubclass(other, self.__class__):
|
| 825 |
+
return True
|
| 826 |
+
if isinstance(other, self.__class__):
|
| 827 |
+
return self.fields == other.fields
|
| 828 |
+
return False
|
| 829 |
+
|
| 830 |
+
def __hash__(self) -> int:
|
| 831 |
+
return hash((self.__class__, tuple(self.fields)))
|
| 832 |
+
|
| 833 |
+
def __iter__(self) -> Iterator[tuple[str, IntoDType]]: # pragma: no cover
|
| 834 |
+
for fld in self.fields:
|
| 835 |
+
yield fld.name, fld.dtype
|
| 836 |
+
|
| 837 |
+
def __reversed__(self) -> Iterator[tuple[str, IntoDType]]:
|
| 838 |
+
for fld in reversed(self.fields):
|
| 839 |
+
yield fld.name, fld.dtype
|
| 840 |
+
|
| 841 |
+
def __repr__(self) -> str:
|
| 842 |
+
class_name = self.__class__.__name__
|
| 843 |
+
return f"{class_name}({dict(self)})"
|
| 844 |
+
|
| 845 |
+
def to_schema(self) -> OrderedDict[str, IntoDType]:
|
| 846 |
+
"""Return Struct dtype as a schema dict."""
|
| 847 |
+
return OrderedDict(self)
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
class List(NestedType):
|
| 851 |
+
"""Variable length list type.
|
| 852 |
+
|
| 853 |
+
Examples:
|
| 854 |
+
>>> import pandas as pd
|
| 855 |
+
>>> import pyarrow as pa
|
| 856 |
+
>>> import narwhals as nw
|
| 857 |
+
>>> s_native = pd.Series(
|
| 858 |
+
... [["narwhal", "orca"], ["beluga", "vaquita"]],
|
| 859 |
+
... dtype=pd.ArrowDtype(pa.large_list(pa.large_string())),
|
| 860 |
+
... )
|
| 861 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 862 |
+
List(String)
|
| 863 |
+
"""
|
| 864 |
+
|
| 865 |
+
__slots__ = ("inner",)
|
| 866 |
+
inner: IntoDType
|
| 867 |
+
"""The DType of the values within each list."""
|
| 868 |
+
|
| 869 |
+
def __init__(self, inner: IntoDType) -> None:
|
| 870 |
+
self.inner = inner
|
| 871 |
+
|
| 872 |
+
def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override]
|
| 873 |
+
"""Check if this List is equivalent to another DType.
|
| 874 |
+
|
| 875 |
+
Examples:
|
| 876 |
+
>>> import narwhals as nw
|
| 877 |
+
>>> nw.List(nw.Int64) == nw.List(nw.Int64)
|
| 878 |
+
True
|
| 879 |
+
>>> nw.List(nw.Int64) == nw.List(nw.Float32)
|
| 880 |
+
False
|
| 881 |
+
|
| 882 |
+
If a parent type is not specific about its inner type, we infer it as equal
|
| 883 |
+
|
| 884 |
+
>>> nw.List(nw.Int64) == nw.List
|
| 885 |
+
True
|
| 886 |
+
"""
|
| 887 |
+
if type(other) is DTypeClass and issubclass(other, self.__class__):
|
| 888 |
+
return True
|
| 889 |
+
if isinstance(other, self.__class__):
|
| 890 |
+
return self.inner == other.inner
|
| 891 |
+
return False
|
| 892 |
+
|
| 893 |
+
def __hash__(self) -> int:
|
| 894 |
+
return hash((self.__class__, self.inner))
|
| 895 |
+
|
| 896 |
+
def __repr__(self) -> str:
|
| 897 |
+
class_name = self.__class__.__name__
|
| 898 |
+
return f"{class_name}({self.inner!r})"
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
class Array(NestedType):
|
| 902 |
+
"""Fixed length list type.
|
| 903 |
+
|
| 904 |
+
Arguments:
|
| 905 |
+
inner: The datatype of the values within each array.
|
| 906 |
+
shape: The shape of the arrays.
|
| 907 |
+
|
| 908 |
+
Examples:
|
| 909 |
+
>>> import polars as pl
|
| 910 |
+
>>> import narwhals as nw
|
| 911 |
+
>>> s_native = pl.Series([[1, 2], [3, 4], [5, 6]], dtype=pl.Array(pl.Int32, 2))
|
| 912 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 913 |
+
Array(Int32, shape=(2,))
|
| 914 |
+
"""
|
| 915 |
+
|
| 916 |
+
__slots__ = ("inner", "shape", "size")
|
| 917 |
+
inner: IntoDType
|
| 918 |
+
"""The DType of the values within each array."""
|
| 919 |
+
size: int
|
| 920 |
+
"""The size of the Array."""
|
| 921 |
+
shape: tuple[int, ...]
|
| 922 |
+
"""The shape of the arrays."""
|
| 923 |
+
|
| 924 |
+
def __init__(self, inner: IntoDType, shape: int | tuple[int, ...]) -> None:
|
| 925 |
+
inner_shape: tuple[int, ...] = inner.shape if isinstance(inner, Array) else ()
|
| 926 |
+
if isinstance(shape, int):
|
| 927 |
+
self.inner = inner
|
| 928 |
+
self.size = shape
|
| 929 |
+
self.shape = (shape, *inner_shape)
|
| 930 |
+
|
| 931 |
+
elif isinstance(shape, tuple) and len(shape) != 0 and isinstance(shape[0], int):
|
| 932 |
+
if len(shape) > 1:
|
| 933 |
+
inner = Array(inner, shape[1:])
|
| 934 |
+
|
| 935 |
+
self.inner = inner
|
| 936 |
+
self.size = shape[0]
|
| 937 |
+
self.shape = shape + inner_shape
|
| 938 |
+
|
| 939 |
+
else:
|
| 940 |
+
msg = f"invalid input for shape: {shape!r}"
|
| 941 |
+
raise TypeError(msg)
|
| 942 |
+
|
| 943 |
+
def __eq__(self, other: DType | type[DType]) -> bool: # type: ignore[override]
|
| 944 |
+
"""Check if this Array is equivalent to another DType.
|
| 945 |
+
|
| 946 |
+
Examples:
|
| 947 |
+
>>> import narwhals as nw
|
| 948 |
+
>>> nw.Array(nw.Int64, 2) == nw.Array(nw.Int64, 2)
|
| 949 |
+
True
|
| 950 |
+
>>> nw.Array(nw.Int64, 2) == nw.Array(nw.String, 2)
|
| 951 |
+
False
|
| 952 |
+
>>> nw.Array(nw.Int64, 2) == nw.Array(nw.Int64, 4)
|
| 953 |
+
False
|
| 954 |
+
|
| 955 |
+
If a parent type is not specific about its inner type, we infer it as equal
|
| 956 |
+
|
| 957 |
+
>>> nw.Array(nw.Int64, 2) == nw.Array
|
| 958 |
+
True
|
| 959 |
+
"""
|
| 960 |
+
if type(other) is DTypeClass and issubclass(other, self.__class__):
|
| 961 |
+
return True
|
| 962 |
+
if isinstance(other, self.__class__):
|
| 963 |
+
if self.shape != other.shape:
|
| 964 |
+
return False
|
| 965 |
+
return self.inner == other.inner
|
| 966 |
+
return False
|
| 967 |
+
|
| 968 |
+
def __hash__(self) -> int:
|
| 969 |
+
return hash((self.__class__, self.inner, self.shape))
|
| 970 |
+
|
| 971 |
+
def __repr__(self) -> str:
|
| 972 |
+
# Get leaf type
|
| 973 |
+
dtype_ = self
|
| 974 |
+
for _ in self.shape:
|
| 975 |
+
dtype_ = dtype_.inner # type: ignore[assignment]
|
| 976 |
+
|
| 977 |
+
class_name = self.__class__.__name__
|
| 978 |
+
return f"{class_name}({dtype_!r}, shape={self.shape})"
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
class Date(TemporalType):
|
| 982 |
+
"""Data type representing a calendar date.
|
| 983 |
+
|
| 984 |
+
Examples:
|
| 985 |
+
>>> from datetime import date, timedelta
|
| 986 |
+
>>> import pyarrow as pa
|
| 987 |
+
>>> import narwhals as nw
|
| 988 |
+
>>> s_native = pa.chunked_array(
|
| 989 |
+
... [[date(2024, 12, 1) + timedelta(days=d) for d in range(4)]]
|
| 990 |
+
... )
|
| 991 |
+
>>> nw.from_native(s_native, series_only=True).dtype
|
| 992 |
+
Date
|
| 993 |
+
"""
|
| 994 |
+
|
| 995 |
+
|
| 996 |
+
class Time(TemporalType):
|
| 997 |
+
"""Data type representing the time of day.
|
| 998 |
+
|
| 999 |
+
Examples:
|
| 1000 |
+
>>> import polars as pl
|
| 1001 |
+
>>> import pyarrow as pa
|
| 1002 |
+
>>> import narwhals as nw
|
| 1003 |
+
>>> import duckdb
|
| 1004 |
+
>>> from datetime import time
|
| 1005 |
+
>>> data = [time(9, 0), time(9, 1, 10), time(9, 2)]
|
| 1006 |
+
>>> ser_pl = pl.Series(data)
|
| 1007 |
+
>>> ser_pa = pa.chunked_array([pa.array(data, type=pa.time64("ns"))])
|
| 1008 |
+
>>> rel = duckdb.sql(
|
| 1009 |
+
... " SELECT * FROM (VALUES (TIME '12:00:00'), (TIME '14:30:15')) df(t)"
|
| 1010 |
+
... )
|
| 1011 |
+
|
| 1012 |
+
>>> nw.from_native(ser_pl, series_only=True).dtype
|
| 1013 |
+
Time
|
| 1014 |
+
>>> nw.from_native(ser_pa, series_only=True).dtype
|
| 1015 |
+
Time
|
| 1016 |
+
>>> nw.from_native(rel).collect_schema()["t"]
|
| 1017 |
+
Time
|
| 1018 |
+
"""
|
| 1019 |
+
|
| 1020 |
+
|
| 1021 |
+
class Binary(DType):
|
| 1022 |
+
"""Binary type.
|
| 1023 |
+
|
| 1024 |
+
Examples:
|
| 1025 |
+
>>> import polars as pl
|
| 1026 |
+
>>> import narwhals as nw
|
| 1027 |
+
>>> import pyarrow as pa
|
| 1028 |
+
>>> import duckdb
|
| 1029 |
+
>>> data = [b"test1", b"test2"]
|
| 1030 |
+
>>> ser_pl = pl.Series(data, dtype=pl.Binary)
|
| 1031 |
+
>>> ser_pa = pa.chunked_array([pa.array(data, type=pa.binary())])
|
| 1032 |
+
>>> rel = duckdb.sql(
|
| 1033 |
+
... "SELECT * FROM (VALUES (BLOB 'test1'), (BLOB 'test2')) AS df(t)"
|
| 1034 |
+
... )
|
| 1035 |
+
|
| 1036 |
+
>>> nw.from_native(ser_pl, series_only=True).dtype
|
| 1037 |
+
Binary
|
| 1038 |
+
>>> nw.from_native(ser_pa, series_only=True).dtype
|
| 1039 |
+
Binary
|
| 1040 |
+
>>> nw.from_native(rel).collect_schema()["t"]
|
| 1041 |
+
Binary
|
| 1042 |
+
"""
|
.venv_haddock/lib/python3.12/site-packages/narwhals/exceptions.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
if TYPE_CHECKING:
|
| 6 |
+
from collections.abc import Collection, Iterable
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class NarwhalsError(ValueError):
|
| 10 |
+
"""Base class for all Narwhals exceptions."""
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class FormattedKeyError(KeyError):
|
| 14 |
+
"""KeyError with formatted error message.
|
| 15 |
+
|
| 16 |
+
Python's `KeyError` has special casing around formatting
|
| 17 |
+
(see https://bugs.python.org/issue2651). Use this class when the error
|
| 18 |
+
message has newlines and other special format characters.
|
| 19 |
+
Needed by https://github.com/tensorflow/tensorflow/issues/36857.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
message: str
|
| 23 |
+
|
| 24 |
+
def __init__(self, message: str) -> None:
|
| 25 |
+
self.message = message
|
| 26 |
+
|
| 27 |
+
def __str__(self) -> str:
|
| 28 |
+
return self.message
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ColumnNotFoundError(FormattedKeyError, NarwhalsError):
|
| 32 |
+
"""Exception raised when column name isn't present."""
|
| 33 |
+
|
| 34 |
+
message: str
|
| 35 |
+
|
| 36 |
+
def __init__(self, message: str) -> None:
|
| 37 |
+
self.message = message
|
| 38 |
+
super().__init__(self.message)
|
| 39 |
+
|
| 40 |
+
@classmethod
|
| 41 |
+
def from_missing_and_available_column_names(
|
| 42 |
+
cls, missing_columns: Iterable[str], available_columns: Collection[str], /
|
| 43 |
+
) -> ColumnNotFoundError:
|
| 44 |
+
message = (
|
| 45 |
+
f"The following columns were not found: {sorted(missing_columns)}"
|
| 46 |
+
f"\n\nHint: Did you mean one of these columns: {list(available_columns)}?"
|
| 47 |
+
)
|
| 48 |
+
return ColumnNotFoundError(message)
|
| 49 |
+
|
| 50 |
+
@classmethod
|
| 51 |
+
def from_available_column_names(
|
| 52 |
+
cls, available_columns: Collection[str]
|
| 53 |
+
) -> ColumnNotFoundError:
|
| 54 |
+
message = (
|
| 55 |
+
"The selected columns were not found."
|
| 56 |
+
f"\n\nHint: Did you mean one of these columns: {list(available_columns)}?"
|
| 57 |
+
)
|
| 58 |
+
return ColumnNotFoundError(message)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class ComputeError(NarwhalsError):
|
| 62 |
+
"""Exception raised when the underlying computation could not be evaluated."""
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class ShapeError(NarwhalsError):
|
| 66 |
+
"""Exception raised when trying to perform operations on data structures with incompatible shapes."""
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class MultiOutputExpressionError(NarwhalsError):
|
| 70 |
+
"""Exception raised when using multi-output expression in unsupported context."""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class DuplicateError(NarwhalsError):
|
| 74 |
+
"""Exception when duplicate column names are encountered."""
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class InvalidOperationError(NarwhalsError):
|
| 78 |
+
"""Exception raised during invalid operations."""
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class InvalidIntoExprError(TypeError, NarwhalsError):
|
| 82 |
+
"""Exception raised when object can't be converted to expression."""
|
| 83 |
+
|
| 84 |
+
message: str
|
| 85 |
+
|
| 86 |
+
def __init__(self, message: str) -> None:
|
| 87 |
+
self.message = message
|
| 88 |
+
super().__init__(self.message)
|
| 89 |
+
|
| 90 |
+
@classmethod
|
| 91 |
+
def from_invalid_type(cls: type, invalid_type: type) -> InvalidIntoExprError:
|
| 92 |
+
message = (
|
| 93 |
+
f"Expected an object which can be converted into an expression, got {invalid_type}\n\n"
|
| 94 |
+
"Hint:\n"
|
| 95 |
+
"- if you were trying to select a column which does not have a string\n"
|
| 96 |
+
" column name, then you should explicitly use `nw.col`.\n"
|
| 97 |
+
" For example, `df.select(nw.col(0))` if you have a column named `0`.\n"
|
| 98 |
+
"- if you were trying to create a new literal column, then you \n"
|
| 99 |
+
" should explicitly use `nw.lit`.\n"
|
| 100 |
+
" For example, `df.select(nw.lit(0))` if you want to create a new\n"
|
| 101 |
+
" column with literal value `0`."
|
| 102 |
+
)
|
| 103 |
+
return InvalidIntoExprError(message)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class UnsupportedDTypeError(NarwhalsError):
|
| 107 |
+
"""Exception raised when trying to convert to a DType which is not supported by the given backend."""
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class NarwhalsUnstableWarning(UserWarning):
|
| 111 |
+
"""Warning issued when a method or function is considered unstable in the stable api."""
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class PerformanceWarning(Warning): ...
|
.venv_haddock/lib/python3.12/site-packages/narwhals/expr.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/expr_cat.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Generic, TypeVar
|
| 4 |
+
|
| 5 |
+
from narwhals._expression_parsing import ExprKind, ExprNode
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from narwhals.expr import Expr
|
| 9 |
+
|
| 10 |
+
ExprT = TypeVar("ExprT", bound="Expr")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ExprCatNamespace(Generic[ExprT]):
|
| 14 |
+
def __init__(self, expr: ExprT) -> None:
|
| 15 |
+
self._expr = expr
|
| 16 |
+
|
| 17 |
+
def get_categories(self) -> ExprT:
|
| 18 |
+
"""Get unique categories from column.
|
| 19 |
+
|
| 20 |
+
Examples:
|
| 21 |
+
>>> import polars as pl
|
| 22 |
+
>>> import narwhals as nw
|
| 23 |
+
>>> df_native = pl.DataFrame(
|
| 24 |
+
... {"fruits": ["apple", "mango", "mango"]},
|
| 25 |
+
... schema={"fruits": pl.Categorical},
|
| 26 |
+
... )
|
| 27 |
+
>>> df = nw.from_native(df_native)
|
| 28 |
+
>>> df.select(nw.col("fruits").cat.get_categories()).to_native()
|
| 29 |
+
shape: (2, 1)
|
| 30 |
+
┌────────┐
|
| 31 |
+
│ fruits │
|
| 32 |
+
│ --- │
|
| 33 |
+
│ str │
|
| 34 |
+
╞════════╡
|
| 35 |
+
│ apple │
|
| 36 |
+
│ mango │
|
| 37 |
+
└────────┘
|
| 38 |
+
"""
|
| 39 |
+
return self._expr._append_node(
|
| 40 |
+
ExprNode(ExprKind.FILTRATION, "cat.get_categories")
|
| 41 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/expr_dt.py
ADDED
|
@@ -0,0 +1,738 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Generic, TypeVar
|
| 4 |
+
|
| 5 |
+
from narwhals._expression_parsing import ExprKind, ExprNode
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from narwhals.expr import Expr
|
| 9 |
+
from narwhals.typing import TimeUnit
|
| 10 |
+
|
| 11 |
+
ExprT = TypeVar("ExprT", bound="Expr")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ExprDateTimeNamespace(Generic[ExprT]):
|
| 15 |
+
def __init__(self, expr: ExprT) -> None:
|
| 16 |
+
self._expr = expr
|
| 17 |
+
|
| 18 |
+
def date(self) -> ExprT:
|
| 19 |
+
"""Extract the date from underlying DateTime representation.
|
| 20 |
+
|
| 21 |
+
Raises:
|
| 22 |
+
NotImplementedError: If pandas default backend is being used.
|
| 23 |
+
|
| 24 |
+
Examples:
|
| 25 |
+
>>> from datetime import datetime
|
| 26 |
+
>>> import polars as pl
|
| 27 |
+
>>> import narwhals as nw
|
| 28 |
+
>>> df_native = pl.DataFrame(
|
| 29 |
+
... {"a": [datetime(2012, 1, 7, 10), datetime(2027, 12, 13)]}
|
| 30 |
+
... )
|
| 31 |
+
>>> df = nw.from_native(df_native)
|
| 32 |
+
>>> df.select(nw.col("a").dt.date()).to_native()
|
| 33 |
+
shape: (2, 1)
|
| 34 |
+
┌────────────┐
|
| 35 |
+
│ a │
|
| 36 |
+
│ --- │
|
| 37 |
+
│ date │
|
| 38 |
+
╞════════════╡
|
| 39 |
+
│ 2012-01-07 │
|
| 40 |
+
│ 2027-12-13 │
|
| 41 |
+
└────────────┘
|
| 42 |
+
"""
|
| 43 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.date"))
|
| 44 |
+
|
| 45 |
+
def year(self) -> ExprT:
|
| 46 |
+
"""Extract year from underlying DateTime representation.
|
| 47 |
+
|
| 48 |
+
Returns the year number in the calendar date.
|
| 49 |
+
|
| 50 |
+
Examples:
|
| 51 |
+
>>> from datetime import datetime
|
| 52 |
+
>>> import pandas as pd
|
| 53 |
+
>>> import narwhals as nw
|
| 54 |
+
>>> df_native = pd.DataFrame(
|
| 55 |
+
... {"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]}
|
| 56 |
+
... )
|
| 57 |
+
>>> df = nw.from_native(df_native)
|
| 58 |
+
>>> df.with_columns(nw.col("a").dt.year().alias("year"))
|
| 59 |
+
┌──────────────────┐
|
| 60 |
+
|Narwhals DataFrame|
|
| 61 |
+
|------------------|
|
| 62 |
+
| a year|
|
| 63 |
+
|0 1978-06-01 1978|
|
| 64 |
+
|1 2065-01-01 2065|
|
| 65 |
+
└──────────────────┘
|
| 66 |
+
"""
|
| 67 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.year"))
|
| 68 |
+
|
| 69 |
+
def month(self) -> ExprT:
|
| 70 |
+
"""Extract month from underlying DateTime representation.
|
| 71 |
+
|
| 72 |
+
Returns the month number starting from 1. The return value ranges from 1 to 12.
|
| 73 |
+
|
| 74 |
+
Examples:
|
| 75 |
+
>>> from datetime import datetime
|
| 76 |
+
>>> import pyarrow as pa
|
| 77 |
+
>>> import narwhals as nw
|
| 78 |
+
>>> df_native = pa.table({"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]})
|
| 79 |
+
>>> df = nw.from_native(df_native)
|
| 80 |
+
>>> df.with_columns(nw.col("a").dt.month().alias("month")).to_native()
|
| 81 |
+
pyarrow.Table
|
| 82 |
+
a: timestamp[us]
|
| 83 |
+
month: int64
|
| 84 |
+
----
|
| 85 |
+
a: [[1978-06-01 00:00:00.000000,2065-01-01 00:00:00.000000]]
|
| 86 |
+
month: [[6,1]]
|
| 87 |
+
"""
|
| 88 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.month"))
|
| 89 |
+
|
| 90 |
+
def day(self) -> ExprT:
|
| 91 |
+
"""Extract day from underlying DateTime representation.
|
| 92 |
+
|
| 93 |
+
Returns the day of month starting from 1. The return value ranges from 1 to 31. (The last day of month differs by months.)
|
| 94 |
+
|
| 95 |
+
Examples:
|
| 96 |
+
>>> from datetime import datetime
|
| 97 |
+
>>> import pyarrow as pa
|
| 98 |
+
>>> import narwhals as nw
|
| 99 |
+
>>> df_native = pa.table({"a": [datetime(1978, 6, 1), datetime(2065, 1, 1)]})
|
| 100 |
+
>>> df = nw.from_native(df_native)
|
| 101 |
+
>>> df.with_columns(nw.col("a").dt.day().alias("day")).to_native()
|
| 102 |
+
pyarrow.Table
|
| 103 |
+
a: timestamp[us]
|
| 104 |
+
day: int64
|
| 105 |
+
----
|
| 106 |
+
a: [[1978-06-01 00:00:00.000000,2065-01-01 00:00:00.000000]]
|
| 107 |
+
day: [[1,1]]
|
| 108 |
+
"""
|
| 109 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.day"))
|
| 110 |
+
|
| 111 |
+
def hour(self) -> ExprT:
|
| 112 |
+
"""Extract hour from underlying DateTime representation.
|
| 113 |
+
|
| 114 |
+
Returns the hour number from 0 to 23.
|
| 115 |
+
|
| 116 |
+
Examples:
|
| 117 |
+
>>> from datetime import datetime
|
| 118 |
+
>>> import polars as pl
|
| 119 |
+
>>> import narwhals as nw
|
| 120 |
+
>>> df_native = pl.DataFrame(
|
| 121 |
+
... {"a": [datetime(1978, 1, 1, 1), datetime(2065, 1, 1, 10)]}
|
| 122 |
+
... )
|
| 123 |
+
>>> df = nw.from_native(df_native)
|
| 124 |
+
>>> df.with_columns(nw.col("a").dt.hour().alias("hour"))
|
| 125 |
+
┌──────────────────────────────┐
|
| 126 |
+
| Narwhals DataFrame |
|
| 127 |
+
|------------------------------|
|
| 128 |
+
|shape: (2, 2) |
|
| 129 |
+
|┌─────────────────────┬──────┐|
|
| 130 |
+
|│ a ┆ hour │|
|
| 131 |
+
|│ --- ┆ --- │|
|
| 132 |
+
|│ datetime[μs] ┆ i8 │|
|
| 133 |
+
|╞═════════════════════╪══════╡|
|
| 134 |
+
|│ 1978-01-01 01:00:00 ┆ 1 │|
|
| 135 |
+
|│ 2065-01-01 10:00:00 ┆ 10 │|
|
| 136 |
+
|└─────────────────────┴──────┘|
|
| 137 |
+
└──────────────────────────────┘
|
| 138 |
+
"""
|
| 139 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.hour"))
|
| 140 |
+
|
| 141 |
+
def minute(self) -> ExprT:
|
| 142 |
+
"""Extract minutes from underlying DateTime representation.
|
| 143 |
+
|
| 144 |
+
Returns the minute number from 0 to 59.
|
| 145 |
+
|
| 146 |
+
Examples:
|
| 147 |
+
>>> from datetime import datetime
|
| 148 |
+
>>> import pandas as pd
|
| 149 |
+
>>> import narwhals as nw
|
| 150 |
+
>>> df_native = pd.DataFrame(
|
| 151 |
+
... {"a": [datetime(1978, 1, 1, 1, 1), datetime(2065, 1, 1, 10, 20)]}
|
| 152 |
+
... )
|
| 153 |
+
>>> df = nw.from_native(df_native)
|
| 154 |
+
>>> df.with_columns(nw.col("a").dt.minute().alias("minute")).to_native()
|
| 155 |
+
a minute
|
| 156 |
+
0 1978-01-01 01:01:00 1
|
| 157 |
+
1 2065-01-01 10:20:00 20
|
| 158 |
+
"""
|
| 159 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.minute"))
|
| 160 |
+
|
| 161 |
+
def second(self) -> ExprT:
|
| 162 |
+
"""Extract seconds from underlying DateTime representation.
|
| 163 |
+
|
| 164 |
+
Examples:
|
| 165 |
+
>>> from datetime import datetime
|
| 166 |
+
>>> import pyarrow as pa
|
| 167 |
+
>>> import narwhals as nw
|
| 168 |
+
>>> df_native = pa.table(
|
| 169 |
+
... {
|
| 170 |
+
... "a": [
|
| 171 |
+
... datetime(1978, 1, 1, 1, 1, 1),
|
| 172 |
+
... datetime(2065, 1, 1, 10, 20, 30),
|
| 173 |
+
... ]
|
| 174 |
+
... }
|
| 175 |
+
... )
|
| 176 |
+
>>> df = nw.from_native(df_native)
|
| 177 |
+
>>> df.with_columns(nw.col("a").dt.second().alias("second")).to_native()
|
| 178 |
+
pyarrow.Table
|
| 179 |
+
a: timestamp[us]
|
| 180 |
+
second: int64
|
| 181 |
+
----
|
| 182 |
+
a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.000000]]
|
| 183 |
+
second: [[1,30]]
|
| 184 |
+
"""
|
| 185 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.second"))
|
| 186 |
+
|
| 187 |
+
def millisecond(self) -> ExprT:
|
| 188 |
+
"""Extract milliseconds from underlying DateTime representation.
|
| 189 |
+
|
| 190 |
+
Examples:
|
| 191 |
+
>>> from datetime import datetime
|
| 192 |
+
>>> import pyarrow as pa
|
| 193 |
+
>>> import narwhals as nw
|
| 194 |
+
>>> df_native = pa.table(
|
| 195 |
+
... {
|
| 196 |
+
... "a": [
|
| 197 |
+
... datetime(1978, 1, 1, 1, 1, 1, 0),
|
| 198 |
+
... datetime(2065, 1, 1, 10, 20, 30, 67000),
|
| 199 |
+
... ]
|
| 200 |
+
... }
|
| 201 |
+
... )
|
| 202 |
+
>>> df = nw.from_native(df_native)
|
| 203 |
+
>>> df.with_columns(
|
| 204 |
+
... nw.col("a").dt.millisecond().alias("millisecond")
|
| 205 |
+
... ).to_native()
|
| 206 |
+
pyarrow.Table
|
| 207 |
+
a: timestamp[us]
|
| 208 |
+
millisecond: int64
|
| 209 |
+
----
|
| 210 |
+
a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]]
|
| 211 |
+
millisecond: [[0,67]]
|
| 212 |
+
"""
|
| 213 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.millisecond"))
|
| 214 |
+
|
| 215 |
+
def microsecond(self) -> ExprT:
|
| 216 |
+
"""Extract microseconds from underlying DateTime representation.
|
| 217 |
+
|
| 218 |
+
Examples:
|
| 219 |
+
>>> from datetime import datetime
|
| 220 |
+
>>> import pyarrow as pa
|
| 221 |
+
>>> import narwhals as nw
|
| 222 |
+
>>> df_native = pa.table(
|
| 223 |
+
... {
|
| 224 |
+
... "a": [
|
| 225 |
+
... datetime(1978, 1, 1, 1, 1, 1, 0),
|
| 226 |
+
... datetime(2065, 1, 1, 10, 20, 30, 67000),
|
| 227 |
+
... ]
|
| 228 |
+
... }
|
| 229 |
+
... )
|
| 230 |
+
>>> df = nw.from_native(df_native)
|
| 231 |
+
>>> df.with_columns(
|
| 232 |
+
... nw.col("a").dt.microsecond().alias("microsecond")
|
| 233 |
+
... ).to_native()
|
| 234 |
+
pyarrow.Table
|
| 235 |
+
a: timestamp[us]
|
| 236 |
+
microsecond: int64
|
| 237 |
+
----
|
| 238 |
+
a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]]
|
| 239 |
+
microsecond: [[0,67000]]
|
| 240 |
+
"""
|
| 241 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.microsecond"))
|
| 242 |
+
|
| 243 |
+
def nanosecond(self) -> ExprT:
|
| 244 |
+
"""Extract Nanoseconds from underlying DateTime representation.
|
| 245 |
+
|
| 246 |
+
Examples:
|
| 247 |
+
>>> from datetime import datetime
|
| 248 |
+
>>> import pyarrow as pa
|
| 249 |
+
>>> import narwhals as nw
|
| 250 |
+
>>> df_native = pa.table(
|
| 251 |
+
... {
|
| 252 |
+
... "a": [
|
| 253 |
+
... datetime(1978, 1, 1, 1, 1, 1, 0),
|
| 254 |
+
... datetime(2065, 1, 1, 10, 20, 30, 67000),
|
| 255 |
+
... ]
|
| 256 |
+
... }
|
| 257 |
+
... )
|
| 258 |
+
>>> df = nw.from_native(df_native)
|
| 259 |
+
>>> df.with_columns(
|
| 260 |
+
... nw.col("a").dt.nanosecond().alias("nanosecond")
|
| 261 |
+
... ).to_native()
|
| 262 |
+
pyarrow.Table
|
| 263 |
+
a: timestamp[us]
|
| 264 |
+
nanosecond: int64
|
| 265 |
+
----
|
| 266 |
+
a: [[1978-01-01 01:01:01.000000,2065-01-01 10:20:30.067000]]
|
| 267 |
+
nanosecond: [[0,67000000]]
|
| 268 |
+
"""
|
| 269 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.nanosecond"))
|
| 270 |
+
|
| 271 |
+
def ordinal_day(self) -> ExprT:
|
| 272 |
+
"""Get ordinal day.
|
| 273 |
+
|
| 274 |
+
Examples:
|
| 275 |
+
>>> from datetime import datetime
|
| 276 |
+
>>> import pandas as pd
|
| 277 |
+
>>> import narwhals as nw
|
| 278 |
+
>>> df_native = pd.DataFrame(
|
| 279 |
+
... {"a": [datetime(2020, 1, 1), datetime(2020, 8, 3)]}
|
| 280 |
+
... )
|
| 281 |
+
>>> df = nw.from_native(df_native)
|
| 282 |
+
>>> df.with_columns(a_ordinal_day=nw.col("a").dt.ordinal_day())
|
| 283 |
+
┌───────────────────────────┐
|
| 284 |
+
| Narwhals DataFrame |
|
| 285 |
+
|---------------------------|
|
| 286 |
+
| a a_ordinal_day|
|
| 287 |
+
|0 2020-01-01 1|
|
| 288 |
+
|1 2020-08-03 216|
|
| 289 |
+
└───────────────────────────┘
|
| 290 |
+
"""
|
| 291 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.ordinal_day"))
|
| 292 |
+
|
| 293 |
+
def weekday(self) -> ExprT:
|
| 294 |
+
"""Extract the week day from the underlying Date representation.
|
| 295 |
+
|
| 296 |
+
Note that Monday = 1 and Sunday = 7.
|
| 297 |
+
|
| 298 |
+
Examples:
|
| 299 |
+
>>> from datetime import datetime
|
| 300 |
+
>>> import pandas as pd
|
| 301 |
+
>>> import narwhals as nw
|
| 302 |
+
>>> df_native = pd.DataFrame(
|
| 303 |
+
... {"a": [datetime(2020, 1, 1), datetime(2020, 8, 3)]}
|
| 304 |
+
... )
|
| 305 |
+
>>> df = nw.from_native(df_native)
|
| 306 |
+
>>> df.with_columns(a_week_day=nw.col("a").dt.weekday())
|
| 307 |
+
┌────────────────────────┐
|
| 308 |
+
| Narwhals DataFrame |
|
| 309 |
+
|------------------------|
|
| 310 |
+
| a a_week_day|
|
| 311 |
+
|0 2020-01-01 3|
|
| 312 |
+
|1 2020-08-03 1|
|
| 313 |
+
└────────────────────────┘
|
| 314 |
+
"""
|
| 315 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.weekday"))
|
| 316 |
+
|
| 317 |
+
def total_minutes(self) -> ExprT:
|
| 318 |
+
"""Get total minutes.
|
| 319 |
+
|
| 320 |
+
Notes:
|
| 321 |
+
The function outputs the total minutes in the int dtype by default,
|
| 322 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 323 |
+
consider using `fill_null()` and `cast` in this case.
|
| 324 |
+
|
| 325 |
+
Examples:
|
| 326 |
+
>>> from datetime import timedelta
|
| 327 |
+
>>> import polars as pl
|
| 328 |
+
>>> import narwhals as nw
|
| 329 |
+
>>> df_native = pl.DataFrame(
|
| 330 |
+
... {"a": [timedelta(minutes=10), timedelta(minutes=20, seconds=40)]}
|
| 331 |
+
... )
|
| 332 |
+
>>> df = nw.from_native(df_native)
|
| 333 |
+
>>> df.with_columns(
|
| 334 |
+
... a_total_minutes=nw.col("a").dt.total_minutes()
|
| 335 |
+
... ).to_native()
|
| 336 |
+
shape: (2, 2)
|
| 337 |
+
┌──────────────┬─────────────────┐
|
| 338 |
+
│ a ┆ a_total_minutes │
|
| 339 |
+
│ --- ┆ --- │
|
| 340 |
+
│ duration[μs] ┆ i64 │
|
| 341 |
+
╞══════════════╪═════════════════╡
|
| 342 |
+
│ 10m ┆ 10 │
|
| 343 |
+
│ 20m 40s ┆ 20 │
|
| 344 |
+
└──────────────┴─────────────────┘
|
| 345 |
+
"""
|
| 346 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.total_minutes"))
|
| 347 |
+
|
| 348 |
+
def total_seconds(self) -> ExprT:
|
| 349 |
+
"""Get total seconds.
|
| 350 |
+
|
| 351 |
+
Notes:
|
| 352 |
+
The function outputs the total seconds in the int dtype by default,
|
| 353 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 354 |
+
consider using `fill_null()` and `cast` in this case.
|
| 355 |
+
|
| 356 |
+
Examples:
|
| 357 |
+
>>> from datetime import timedelta
|
| 358 |
+
>>> import polars as pl
|
| 359 |
+
>>> import narwhals as nw
|
| 360 |
+
>>> df_native = pl.DataFrame(
|
| 361 |
+
... {"a": [timedelta(seconds=10), timedelta(seconds=20, milliseconds=40)]}
|
| 362 |
+
... )
|
| 363 |
+
>>> df = nw.from_native(df_native)
|
| 364 |
+
>>> df.with_columns(
|
| 365 |
+
... a_total_seconds=nw.col("a").dt.total_seconds()
|
| 366 |
+
... ).to_native()
|
| 367 |
+
shape: (2, 2)
|
| 368 |
+
┌──────────────┬─────────────────┐
|
| 369 |
+
│ a ┆ a_total_seconds │
|
| 370 |
+
│ --- ┆ --- │
|
| 371 |
+
│ duration[μs] ┆ i64 │
|
| 372 |
+
╞══════════════╪═════════════════╡
|
| 373 |
+
│ 10s ┆ 10 │
|
| 374 |
+
│ 20s 40ms ┆ 20 │
|
| 375 |
+
└──────────────┴─────────────────┘
|
| 376 |
+
"""
|
| 377 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "dt.total_seconds"))
|
| 378 |
+
|
| 379 |
+
def total_milliseconds(self) -> ExprT:
|
| 380 |
+
"""Get total milliseconds.
|
| 381 |
+
|
| 382 |
+
Notes:
|
| 383 |
+
The function outputs the total milliseconds in the int dtype by default,
|
| 384 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 385 |
+
consider using `fill_null()` and `cast` in this case.
|
| 386 |
+
|
| 387 |
+
Examples:
|
| 388 |
+
>>> from datetime import timedelta
|
| 389 |
+
>>> import polars as pl
|
| 390 |
+
>>> import narwhals as nw
|
| 391 |
+
>>> df_native = pl.DataFrame(
|
| 392 |
+
... {
|
| 393 |
+
... "a": [
|
| 394 |
+
... timedelta(milliseconds=10),
|
| 395 |
+
... timedelta(milliseconds=20, microseconds=40),
|
| 396 |
+
... ]
|
| 397 |
+
... }
|
| 398 |
+
... )
|
| 399 |
+
>>> df = nw.from_native(df_native)
|
| 400 |
+
>>> df.with_columns(
|
| 401 |
+
... a_total_milliseconds=nw.col("a").dt.total_milliseconds()
|
| 402 |
+
... ).to_native()
|
| 403 |
+
shape: (2, 2)
|
| 404 |
+
┌──────────────┬──────────────────────┐
|
| 405 |
+
│ a ┆ a_total_milliseconds │
|
| 406 |
+
│ --- ┆ --- │
|
| 407 |
+
│ duration[μs] ┆ i64 │
|
| 408 |
+
╞══════════════╪══════════════════════╡
|
| 409 |
+
│ 10ms ┆ 10 │
|
| 410 |
+
│ 20040µs ┆ 20 │
|
| 411 |
+
└──────────────┴──────────────────────┘
|
| 412 |
+
"""
|
| 413 |
+
return self._expr._append_node(
|
| 414 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.total_milliseconds")
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
def total_microseconds(self) -> ExprT:
|
| 418 |
+
"""Get total microseconds.
|
| 419 |
+
|
| 420 |
+
Notes:
|
| 421 |
+
The function outputs the total microseconds in the int dtype by default,
|
| 422 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 423 |
+
consider using `fill_null()` and `cast` in this case.
|
| 424 |
+
|
| 425 |
+
Examples:
|
| 426 |
+
>>> from datetime import timedelta
|
| 427 |
+
>>> import pyarrow as pa
|
| 428 |
+
>>> import narwhals as nw
|
| 429 |
+
>>> df_native = pa.table(
|
| 430 |
+
... {
|
| 431 |
+
... "a": [
|
| 432 |
+
... timedelta(microseconds=10),
|
| 433 |
+
... timedelta(milliseconds=1, microseconds=200),
|
| 434 |
+
... ]
|
| 435 |
+
... }
|
| 436 |
+
... )
|
| 437 |
+
>>> df = nw.from_native(df_native)
|
| 438 |
+
>>> df.with_columns(
|
| 439 |
+
... a_total_microseconds=nw.col("a").dt.total_microseconds()
|
| 440 |
+
... ).to_native()
|
| 441 |
+
pyarrow.Table
|
| 442 |
+
a: duration[us]
|
| 443 |
+
a_total_microseconds: int64
|
| 444 |
+
----
|
| 445 |
+
a: [[10,1200]]
|
| 446 |
+
a_total_microseconds: [[10,1200]]
|
| 447 |
+
"""
|
| 448 |
+
return self._expr._append_node(
|
| 449 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.total_microseconds")
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
def total_nanoseconds(self) -> ExprT:
|
| 453 |
+
"""Get total nanoseconds.
|
| 454 |
+
|
| 455 |
+
Notes:
|
| 456 |
+
The function outputs the total nanoseconds in the int dtype by default,
|
| 457 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 458 |
+
consider using `fill_null()` and `cast` in this case.
|
| 459 |
+
|
| 460 |
+
Examples:
|
| 461 |
+
>>> from datetime import timedelta
|
| 462 |
+
>>> import pandas as pd
|
| 463 |
+
>>> import narwhals as nw
|
| 464 |
+
>>> df_native = pd.DataFrame(
|
| 465 |
+
... {
|
| 466 |
+
... "a": pd.to_datetime(
|
| 467 |
+
... [
|
| 468 |
+
... "2024-01-01 00:00:00.000000001",
|
| 469 |
+
... "2024-01-01 00:00:00.000000002",
|
| 470 |
+
... ]
|
| 471 |
+
... )
|
| 472 |
+
... }
|
| 473 |
+
... )
|
| 474 |
+
>>> df = nw.from_native(df_native)
|
| 475 |
+
>>> df.with_columns(
|
| 476 |
+
... a_diff_total_nanoseconds=nw.col("a").diff().dt.total_nanoseconds()
|
| 477 |
+
... ).to_native()
|
| 478 |
+
a a_diff_total_nanoseconds
|
| 479 |
+
0 2024-01-01 00:00:00.000000001 NaN
|
| 480 |
+
1 2024-01-01 00:00:00.000000002 1.0
|
| 481 |
+
"""
|
| 482 |
+
return self._expr._append_node(
|
| 483 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.total_nanoseconds")
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
def to_string(self, format: str) -> ExprT:
|
| 487 |
+
"""Convert a Date/Time/Datetime column into a String column with the given format.
|
| 488 |
+
|
| 489 |
+
Arguments:
|
| 490 |
+
format: Format to format temporal column with.
|
| 491 |
+
|
| 492 |
+
Notes:
|
| 493 |
+
Unfortunately, different libraries interpret format directives a bit
|
| 494 |
+
differently.
|
| 495 |
+
|
| 496 |
+
- Chrono, the library used by Polars, uses `"%.f"` for fractional seconds,
|
| 497 |
+
whereas pandas and Python stdlib use `".%f"`.
|
| 498 |
+
- PyArrow interprets `"%S"` as "seconds, including fractional seconds"
|
| 499 |
+
whereas most other tools interpret it as "just seconds, as 2 digits".
|
| 500 |
+
---
|
| 501 |
+
Therefore, we make the following adjustments.
|
| 502 |
+
|
| 503 |
+
- for pandas-like libraries, we replace `"%S.%f"` with `"%S%.f"`.
|
| 504 |
+
- for PyArrow, we replace `"%S.%f"` with `"%S"`.
|
| 505 |
+
---
|
| 506 |
+
Workarounds like these don't make us happy, and we try to avoid them as
|
| 507 |
+
much as possible, but here we feel like it's the best compromise.
|
| 508 |
+
|
| 509 |
+
If you just want to format a date/datetime Series as a local datetime
|
| 510 |
+
string, and have it work as consistently as possible across libraries,
|
| 511 |
+
we suggest using:
|
| 512 |
+
|
| 513 |
+
- `"%Y-%m-%dT%H:%M:%S%.f"` for datetimes
|
| 514 |
+
- `"%Y-%m-%d"` for dates
|
| 515 |
+
---
|
| 516 |
+
Though note that, even then, different tools may return a different number
|
| 517 |
+
of trailing zeros. Nonetheless, this is probably consistent enough for
|
| 518 |
+
most applications.
|
| 519 |
+
|
| 520 |
+
If you have an application where this is not enough, please open an issue
|
| 521 |
+
and let us know.
|
| 522 |
+
|
| 523 |
+
Examples:
|
| 524 |
+
>>> from datetime import datetime
|
| 525 |
+
>>> import polars as pl
|
| 526 |
+
>>> import narwhals as nw
|
| 527 |
+
>>> df_native = pl.DataFrame(
|
| 528 |
+
... {"a": [datetime(2020, 3, 1), datetime(2020, 5, 1)]}
|
| 529 |
+
... )
|
| 530 |
+
>>> df = nw.from_native(df_native)
|
| 531 |
+
>>> df.select(nw.col("a").dt.to_string("%Y/%m/%d %H:%M:%S"))
|
| 532 |
+
┌───────────────────────┐
|
| 533 |
+
| Narwhals DataFrame |
|
| 534 |
+
|-----------------------|
|
| 535 |
+
|shape: (2, 1) |
|
| 536 |
+
|┌─────────────────────┐|
|
| 537 |
+
|│ a │|
|
| 538 |
+
|│ --- │|
|
| 539 |
+
|│ str │|
|
| 540 |
+
|╞═════════════════════╡|
|
| 541 |
+
|│ 2020/03/01 00:00:00 │|
|
| 542 |
+
|│ 2020/05/01 00:00:00 │|
|
| 543 |
+
|└─────────────────────┘|
|
| 544 |
+
└───────────────────────┘
|
| 545 |
+
"""
|
| 546 |
+
return self._expr._append_node(
|
| 547 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.to_string", format=format)
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
def replace_time_zone(self, time_zone: str | None) -> ExprT:
|
| 551 |
+
"""Replace time zone.
|
| 552 |
+
|
| 553 |
+
Arguments:
|
| 554 |
+
time_zone: Target time zone.
|
| 555 |
+
|
| 556 |
+
Examples:
|
| 557 |
+
>>> from datetime import datetime, timezone
|
| 558 |
+
>>> import pandas as pd
|
| 559 |
+
>>> import narwhals as nw
|
| 560 |
+
>>> df_native = pd.DataFrame(
|
| 561 |
+
... {
|
| 562 |
+
... "a": [
|
| 563 |
+
... datetime(2024, 1, 1, tzinfo=timezone.utc),
|
| 564 |
+
... datetime(2024, 1, 2, tzinfo=timezone.utc),
|
| 565 |
+
... ]
|
| 566 |
+
... }
|
| 567 |
+
... )
|
| 568 |
+
>>> df = nw.from_native(df_native)
|
| 569 |
+
>>> df.select(nw.col("a").dt.replace_time_zone("Asia/Kathmandu")).to_native()
|
| 570 |
+
a
|
| 571 |
+
0 2024-01-01 00:00:00+05:45
|
| 572 |
+
1 2024-01-02 00:00:00+05:45
|
| 573 |
+
"""
|
| 574 |
+
return self._expr._append_node(
|
| 575 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.replace_time_zone", time_zone=time_zone)
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
def convert_time_zone(self, time_zone: str) -> ExprT:
|
| 579 |
+
"""Convert to a new time zone.
|
| 580 |
+
|
| 581 |
+
If converting from a time-zone-naive column, then conversion happens
|
| 582 |
+
as if converting from UTC.
|
| 583 |
+
|
| 584 |
+
Arguments:
|
| 585 |
+
time_zone: Target time zone.
|
| 586 |
+
|
| 587 |
+
Examples:
|
| 588 |
+
>>> from datetime import datetime, timezone
|
| 589 |
+
>>> import pandas as pd
|
| 590 |
+
>>> import narwhals as nw
|
| 591 |
+
>>> df_native = pd.DataFrame(
|
| 592 |
+
... {
|
| 593 |
+
... "a": [
|
| 594 |
+
... datetime(2024, 1, 1, tzinfo=timezone.utc),
|
| 595 |
+
... datetime(2024, 1, 2, tzinfo=timezone.utc),
|
| 596 |
+
... ]
|
| 597 |
+
... }
|
| 598 |
+
... )
|
| 599 |
+
>>> df = nw.from_native(df_native)
|
| 600 |
+
>>> df.select(nw.col("a").dt.convert_time_zone("Asia/Kathmandu")).to_native()
|
| 601 |
+
a
|
| 602 |
+
0 2024-01-01 05:45:00+05:45
|
| 603 |
+
1 2024-01-02 05:45:00+05:45
|
| 604 |
+
"""
|
| 605 |
+
if time_zone is None:
|
| 606 |
+
msg = "Target `time_zone` cannot be `None` in `convert_time_zone`. Please use `replace_time_zone(None)` if you want to remove the time zone."
|
| 607 |
+
raise TypeError(msg)
|
| 608 |
+
return self._expr._append_node(
|
| 609 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.convert_time_zone", time_zone=time_zone)
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
def timestamp(self, time_unit: TimeUnit = "us") -> ExprT:
|
| 613 |
+
"""Return a timestamp in the given time unit.
|
| 614 |
+
|
| 615 |
+
Arguments:
|
| 616 |
+
time_unit: One of
|
| 617 |
+
- 'ns': nanosecond.
|
| 618 |
+
- 'us': microsecond.
|
| 619 |
+
- 'ms': millisecond.
|
| 620 |
+
|
| 621 |
+
Examples:
|
| 622 |
+
>>> from datetime import date
|
| 623 |
+
>>> import polars as pl
|
| 624 |
+
>>> import narwhals as nw
|
| 625 |
+
>>> df_native = pl.DataFrame({"date": [date(2001, 1, 1), None]})
|
| 626 |
+
>>> df = nw.from_native(df_native)
|
| 627 |
+
>>> df.with_columns(nw.col("date").dt.timestamp("ms").alias("timestamp_ms"))
|
| 628 |
+
┌─────────────────────────────┐
|
| 629 |
+
| Narwhals DataFrame |
|
| 630 |
+
|-----------------------------|
|
| 631 |
+
|shape: (2, 2) |
|
| 632 |
+
|┌────────────┬──────────────┐|
|
| 633 |
+
|│ date ┆ timestamp_ms │|
|
| 634 |
+
|│ --- ┆ --- │|
|
| 635 |
+
|│ date ┆ i64 │|
|
| 636 |
+
|╞════════════╪══════════════╡|
|
| 637 |
+
|│ 2001-01-01 ┆ 978307200000 │|
|
| 638 |
+
|│ null ┆ null │|
|
| 639 |
+
|└────────────┴──────────────┘|
|
| 640 |
+
└─────────────────────────────┘
|
| 641 |
+
"""
|
| 642 |
+
if time_unit not in {"ns", "us", "ms"}:
|
| 643 |
+
msg = (
|
| 644 |
+
"invalid `time_unit`"
|
| 645 |
+
f"\n\nExpected one of {{'ns', 'us', 'ms'}}, got {time_unit!r}."
|
| 646 |
+
)
|
| 647 |
+
raise ValueError(msg)
|
| 648 |
+
return self._expr._append_node(
|
| 649 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.timestamp", time_unit=time_unit)
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
def truncate(self, every: str) -> ExprT:
|
| 653 |
+
"""Divide the date/datetime range into buckets.
|
| 654 |
+
|
| 655 |
+
Arguments:
|
| 656 |
+
every: Length of bucket. Must be of form `<multiple><unit>`,
|
| 657 |
+
where `multiple` is a positive integer and `unit` is one of
|
| 658 |
+
|
| 659 |
+
- 'ns': nanosecond.
|
| 660 |
+
- 'us': microsecond.
|
| 661 |
+
- 'ms': millisecond.
|
| 662 |
+
- 's': second.
|
| 663 |
+
- 'm': minute.
|
| 664 |
+
- 'h': hour.
|
| 665 |
+
- 'd': day.
|
| 666 |
+
- 'mo': month.
|
| 667 |
+
- 'q': quarter.
|
| 668 |
+
- 'y': year.
|
| 669 |
+
|
| 670 |
+
Examples:
|
| 671 |
+
>>> from datetime import datetime
|
| 672 |
+
>>> import polars as pl
|
| 673 |
+
>>> import narwhals as nw
|
| 674 |
+
>>> df_native = pl.DataFrame({"datetime": [datetime(2021, 3, 1, 12, 34)]})
|
| 675 |
+
>>> df = nw.from_native(df_native)
|
| 676 |
+
>>> df.with_columns(
|
| 677 |
+
... nw.col("datetime").dt.truncate("1h").alias("datetime_trunc")
|
| 678 |
+
... )
|
| 679 |
+
┌─────────────────────────────────────────────┐
|
| 680 |
+
| Narwhals DataFrame |
|
| 681 |
+
|---------------------------------------------|
|
| 682 |
+
|shape: (1, 2) |
|
| 683 |
+
|┌─────────────────────┬─────────────────────┐|
|
| 684 |
+
|│ datetime ┆ datetime_trunc │|
|
| 685 |
+
|│ --- ┆ --- │|
|
| 686 |
+
|│ datetime[μs] ┆ datetime[μs] │|
|
| 687 |
+
|╞═════════════════════╪═════════════════════╡|
|
| 688 |
+
|│ 2021-03-01 12:34:00 ┆ 2021-03-01 12:00:00 │|
|
| 689 |
+
|└─────────────────────┴─────────────────────┘|
|
| 690 |
+
└─────────────────────────────────────────────┘
|
| 691 |
+
"""
|
| 692 |
+
return self._expr._append_node(
|
| 693 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.truncate", every=every)
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
def offset_by(self, by: str) -> ExprT:
|
| 697 |
+
"""Offset this date by a relative time offset.
|
| 698 |
+
|
| 699 |
+
Arguments:
|
| 700 |
+
by: The offset. Must be of form `<multiple><unit>`,
|
| 701 |
+
where `multiple` is a positive integer and `unit` is one of
|
| 702 |
+
|
| 703 |
+
- 'ns': nanosecond.
|
| 704 |
+
- 'us': microsecond.
|
| 705 |
+
- 'ms': millisecond.
|
| 706 |
+
- 's': second.
|
| 707 |
+
- 'm': minute.
|
| 708 |
+
- 'h': hour.
|
| 709 |
+
- 'd': day.
|
| 710 |
+
- 'mo': month.
|
| 711 |
+
- 'q': quarter.
|
| 712 |
+
- 'y': year.
|
| 713 |
+
|
| 714 |
+
Examples:
|
| 715 |
+
>>> from datetime import datetime
|
| 716 |
+
>>> import polars as pl
|
| 717 |
+
>>> import narwhals as nw
|
| 718 |
+
>>> df_native = pl.DataFrame({"datetime": [datetime(2021, 3, 1, 12, 34)]})
|
| 719 |
+
>>> df = nw.from_native(df_native)
|
| 720 |
+
>>> df.with_columns(
|
| 721 |
+
... nw.col("datetime").dt.offset_by("1h").alias("datetime_offset_by_1h")
|
| 722 |
+
... )
|
| 723 |
+
┌───────────────────────────────────────────────┐
|
| 724 |
+
| Narwhals DataFrame |
|
| 725 |
+
|-----------------------------------------------|
|
| 726 |
+
|shape: (1, 2) |
|
| 727 |
+
|┌─────────────────────┬───────────────────────┐|
|
| 728 |
+
|│ datetime ┆ datetime_offset_by_1h │|
|
| 729 |
+
|│ --- ┆ --- │|
|
| 730 |
+
|│ datetime[μs] ┆ datetime[μs] │|
|
| 731 |
+
|╞═════════════════════╪═══════════════════════╡|
|
| 732 |
+
|│ 2021-03-01 12:34:00 ┆ 2021-03-01 13:34:00 │|
|
| 733 |
+
|└─────────────────────┴───────────────────────┘|
|
| 734 |
+
└───────────────────────────────────────────────┘
|
| 735 |
+
"""
|
| 736 |
+
return self._expr._append_node(
|
| 737 |
+
ExprNode(ExprKind.ELEMENTWISE, "dt.offset_by", by=by)
|
| 738 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Generic, TypeVar
|
| 4 |
+
|
| 5 |
+
from narwhals._expression_parsing import ExprKind, ExprNode
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from narwhals.expr import Expr
|
| 9 |
+
from narwhals.typing import NonNestedLiteral
|
| 10 |
+
|
| 11 |
+
ExprT = TypeVar("ExprT", bound="Expr")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ExprListNamespace(Generic[ExprT]):
|
| 15 |
+
def __init__(self, expr: ExprT) -> None:
|
| 16 |
+
self._expr = expr
|
| 17 |
+
|
| 18 |
+
def len(self) -> ExprT:
|
| 19 |
+
"""Return the number of elements in each list.
|
| 20 |
+
|
| 21 |
+
Null values count towards the total.
|
| 22 |
+
|
| 23 |
+
Examples:
|
| 24 |
+
>>> import polars as pl
|
| 25 |
+
>>> import narwhals as nw
|
| 26 |
+
>>> df_native = pl.DataFrame({"a": [[1, 2], [3, 4, None], None, []]})
|
| 27 |
+
>>> df = nw.from_native(df_native)
|
| 28 |
+
>>> df.with_columns(a_len=nw.col("a").list.len())
|
| 29 |
+
┌────────────────────────┐
|
| 30 |
+
| Narwhals DataFrame |
|
| 31 |
+
|------------------------|
|
| 32 |
+
|shape: (4, 2) |
|
| 33 |
+
|┌──────────────┬───────┐|
|
| 34 |
+
|│ a ┆ a_len │|
|
| 35 |
+
|│ --- ┆ --- │|
|
| 36 |
+
|│ list[i64] ┆ u32 │|
|
| 37 |
+
|╞══════════════╪═══════╡|
|
| 38 |
+
|│ [1, 2] ┆ 2 │|
|
| 39 |
+
|│ [3, 4, null] ┆ 3 │|
|
| 40 |
+
|│ null ┆ null │|
|
| 41 |
+
|│ [] ┆ 0 │|
|
| 42 |
+
|└──────────────┴───────┘|
|
| 43 |
+
└────────────────────────┘
|
| 44 |
+
"""
|
| 45 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.len"))
|
| 46 |
+
|
| 47 |
+
def unique(self) -> ExprT:
|
| 48 |
+
"""Get the unique/distinct values in the list.
|
| 49 |
+
|
| 50 |
+
Null values are included in the result. The order of unique values is not guaranteed.
|
| 51 |
+
|
| 52 |
+
Examples:
|
| 53 |
+
>>> import polars as pl
|
| 54 |
+
>>> import narwhals as nw
|
| 55 |
+
>>> df_native = pl.DataFrame({"a": [[1, 1, 2], [3, 3, None], None, []]})
|
| 56 |
+
>>> df = nw.from_native(df_native)
|
| 57 |
+
>>> df.with_columns(a_unique=nw.col("a").list.unique())
|
| 58 |
+
┌────────────────────────────┐
|
| 59 |
+
| Narwhals DataFrame |
|
| 60 |
+
|----------------------------|
|
| 61 |
+
|shape: (4, 2) |
|
| 62 |
+
|┌──────────────┬───────────┐|
|
| 63 |
+
|│ a ┆ a_unique │|
|
| 64 |
+
|│ --- ┆ --- │|
|
| 65 |
+
|│ list[i64] ┆ list[i64] │|
|
| 66 |
+
|╞══════════════╪═══════════╡|
|
| 67 |
+
|│ [1, 1, 2] ┆ [1, 2] │|
|
| 68 |
+
|│ [3, 3, null] ┆ [null, 3] │|
|
| 69 |
+
|│ null ┆ null │|
|
| 70 |
+
|│ [] ┆ [] │|
|
| 71 |
+
|└──────────────┴───────────┘|
|
| 72 |
+
└────────────────────────────┘
|
| 73 |
+
"""
|
| 74 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.unique"))
|
| 75 |
+
|
| 76 |
+
def contains(self, item: NonNestedLiteral) -> ExprT:
|
| 77 |
+
"""Check if sublists contain the given item.
|
| 78 |
+
|
| 79 |
+
Arguments:
|
| 80 |
+
item: Item that will be checked for membership.
|
| 81 |
+
|
| 82 |
+
Examples:
|
| 83 |
+
>>> import polars as pl
|
| 84 |
+
>>> import narwhals as nw
|
| 85 |
+
>>> df_native = pl.DataFrame({"a": [[1, 2], None, []]})
|
| 86 |
+
>>> df = nw.from_native(df_native)
|
| 87 |
+
>>> df.with_columns(a_contains_1=nw.col("a").list.contains(1))
|
| 88 |
+
┌────────────────────────────┐
|
| 89 |
+
| Narwhals DataFrame |
|
| 90 |
+
|----------------------------|
|
| 91 |
+
|shape: (3, 2) |
|
| 92 |
+
|┌───────────┬──────────────┐|
|
| 93 |
+
|│ a ┆ a_contains_1 │|
|
| 94 |
+
|│ --- ┆ --- │|
|
| 95 |
+
|│ list[i64] ┆ bool │|
|
| 96 |
+
|╞═══════════╪══════════════╡|
|
| 97 |
+
|│ [1, 2] ┆ true │|
|
| 98 |
+
|│ null ┆ null │|
|
| 99 |
+
|│ [] ┆ false │|
|
| 100 |
+
|└───────────┴──────────────┘|
|
| 101 |
+
└────────────────────────────┘
|
| 102 |
+
"""
|
| 103 |
+
return self._expr._append_node(
|
| 104 |
+
ExprNode(ExprKind.ELEMENTWISE, "list.contains", item=item)
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def get(self, index: int) -> ExprT:
|
| 108 |
+
"""Return the value by index in each list.
|
| 109 |
+
|
| 110 |
+
Negative indices are not accepted.
|
| 111 |
+
|
| 112 |
+
Examples:
|
| 113 |
+
>>> import polars as pl
|
| 114 |
+
>>> import narwhals as nw
|
| 115 |
+
>>> df_native = pl.DataFrame({"a": [[1, 2], [3, 4, None], [None, 5]]})
|
| 116 |
+
>>> df = nw.from_native(df_native)
|
| 117 |
+
>>> df.with_columns(a_first=nw.col("a").list.get(0))
|
| 118 |
+
┌──────────────────────────┐
|
| 119 |
+
| Narwhals DataFrame |
|
| 120 |
+
|--------------------------|
|
| 121 |
+
|shape: (3, 2) |
|
| 122 |
+
|┌──────────────┬─────────┐|
|
| 123 |
+
|│ a ┆ a_first │|
|
| 124 |
+
|│ --- ┆ --- │|
|
| 125 |
+
|│ list[i64] ┆ i64 │|
|
| 126 |
+
|╞══════════════╪═════════╡|
|
| 127 |
+
|│ [1, 2] ┆ 1 │|
|
| 128 |
+
|│ [3, 4, null] ┆ 3 │|
|
| 129 |
+
|│ [null, 5] ┆ null │|
|
| 130 |
+
|└──────────────┴─────────┘|
|
| 131 |
+
└──────────────────────────┘
|
| 132 |
+
"""
|
| 133 |
+
if not isinstance(index, int):
|
| 134 |
+
msg = (
|
| 135 |
+
f"Index must be of type 'int'. Got type '{type(index).__name__}' instead."
|
| 136 |
+
)
|
| 137 |
+
raise TypeError(msg)
|
| 138 |
+
|
| 139 |
+
if index < 0:
|
| 140 |
+
msg = f"Index {index} is out of bounds: should be greater than or equal to 0."
|
| 141 |
+
raise ValueError(msg)
|
| 142 |
+
|
| 143 |
+
return self._expr._append_node(
|
| 144 |
+
ExprNode(ExprKind.ELEMENTWISE, "list.get", index=index)
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
def min(self) -> ExprT:
|
| 148 |
+
"""Compute the min value of the lists in the array.
|
| 149 |
+
|
| 150 |
+
Examples:
|
| 151 |
+
>>> import duckdb
|
| 152 |
+
>>> import narwhals as nw
|
| 153 |
+
>>> df_native = duckdb.sql("SELECT * FROM VALUES ([1]), ([3, 4, NULL]) df(a)")
|
| 154 |
+
>>> df = nw.from_native(df_native)
|
| 155 |
+
>>> df.with_columns(a_min=nw.col("a").list.min())
|
| 156 |
+
┌────────────────────────┐
|
| 157 |
+
| Narwhals LazyFrame |
|
| 158 |
+
|------------------------|
|
| 159 |
+
|┌──────────────┬───────┐|
|
| 160 |
+
|│ a │ a_min │|
|
| 161 |
+
|│ int32[] │ int32 │|
|
| 162 |
+
|├──────────────┼───────┤|
|
| 163 |
+
|│ [1] │ 1 │|
|
| 164 |
+
|│ [3, 4, NULL] │ 3 │|
|
| 165 |
+
|└──────────────┴───────┘|
|
| 166 |
+
└────────────────────────┘
|
| 167 |
+
"""
|
| 168 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.min"))
|
| 169 |
+
|
| 170 |
+
def max(self) -> ExprT:
|
| 171 |
+
"""Compute the max value of the lists in the array.
|
| 172 |
+
|
| 173 |
+
Examples:
|
| 174 |
+
>>> import polars as pl
|
| 175 |
+
>>> import narwhals as nw
|
| 176 |
+
>>> df_native = pl.DataFrame({"a": [[1], [3, 4, None]]})
|
| 177 |
+
>>> df = nw.from_native(df_native)
|
| 178 |
+
>>> df.with_columns(a_max=nw.col("a").list.max())
|
| 179 |
+
┌────────────────────────┐
|
| 180 |
+
| Narwhals DataFrame |
|
| 181 |
+
|------------------------|
|
| 182 |
+
|shape: (2, 2) |
|
| 183 |
+
|┌──────────────┬───────┐|
|
| 184 |
+
|│ a ┆ a_max │|
|
| 185 |
+
|│ --- ┆ --- │|
|
| 186 |
+
|│ list[i64] ┆ i64 │|
|
| 187 |
+
|╞══════════════╪═══════╡|
|
| 188 |
+
|│ [1] ┆ 1 │|
|
| 189 |
+
|│ [3, 4, null] ┆ 4 │|
|
| 190 |
+
|└──────────────┴───────┘|
|
| 191 |
+
└────────────────────────┘
|
| 192 |
+
"""
|
| 193 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.max"))
|
| 194 |
+
|
| 195 |
+
def mean(self) -> ExprT:
|
| 196 |
+
"""Compute the mean value of the lists in the array.
|
| 197 |
+
|
| 198 |
+
Examples:
|
| 199 |
+
>>> import pyarrow as pa
|
| 200 |
+
>>> import narwhals as nw
|
| 201 |
+
>>> df_native = pa.table({"a": [[1], [3, 4, None]]})
|
| 202 |
+
>>> df = nw.from_native(df_native)
|
| 203 |
+
>>> df.with_columns(a_mean=nw.col("a").list.mean())
|
| 204 |
+
┌──────────────────────┐
|
| 205 |
+
| Narwhals DataFrame |
|
| 206 |
+
|----------------------|
|
| 207 |
+
|pyarrow.Table |
|
| 208 |
+
|a: list<item: int64> |
|
| 209 |
+
| child 0, item: int64|
|
| 210 |
+
|a_mean: double |
|
| 211 |
+
|---- |
|
| 212 |
+
|a: [[[1],[3,4,null]]] |
|
| 213 |
+
|a_mean: [[1,3.5]] |
|
| 214 |
+
└──────────────────────┘
|
| 215 |
+
"""
|
| 216 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.mean"))
|
| 217 |
+
|
| 218 |
+
def median(self) -> ExprT:
|
| 219 |
+
"""Compute the median value of the lists in the array.
|
| 220 |
+
|
| 221 |
+
Examples:
|
| 222 |
+
>>> import duckdb
|
| 223 |
+
>>> import narwhals as nw
|
| 224 |
+
>>> df_native = duckdb.sql("SELECT * FROM VALUES ([1]), ([3, 4, NULL]) df(a)")
|
| 225 |
+
>>> df = nw.from_native(df_native)
|
| 226 |
+
>>> df.with_columns(a_median=nw.col("a").list.median())
|
| 227 |
+
┌───────────────────────────┐
|
| 228 |
+
| Narwhals LazyFrame |
|
| 229 |
+
|---------------------------|
|
| 230 |
+
|┌──────────────┬──────────┐|
|
| 231 |
+
|│ a │ a_median │|
|
| 232 |
+
|│ int32[] │ double │|
|
| 233 |
+
|├──────────────┼──────────┤|
|
| 234 |
+
|│ [1] │ 1.0 │|
|
| 235 |
+
|│ [3, 4, NULL] │ 3.5 │|
|
| 236 |
+
|└──────────────┴──────────┘|
|
| 237 |
+
└───────────────────────────┘
|
| 238 |
+
"""
|
| 239 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.median"))
|
| 240 |
+
|
| 241 |
+
def sum(self) -> ExprT:
|
| 242 |
+
"""Compute the sum value of the lists in the array.
|
| 243 |
+
|
| 244 |
+
Examples:
|
| 245 |
+
>>> import polars as pl
|
| 246 |
+
>>> import narwhals as nw
|
| 247 |
+
>>> df_native = pl.DataFrame({"a": [[1], [3, 4, None]]})
|
| 248 |
+
>>> df = nw.from_native(df_native)
|
| 249 |
+
>>> df.with_columns(a_sum=nw.col("a").list.sum())
|
| 250 |
+
┌────────────────────────┐
|
| 251 |
+
| Narwhals DataFrame |
|
| 252 |
+
|------------------------|
|
| 253 |
+
|shape: (2, 2) |
|
| 254 |
+
|┌──────────────┬───────┐|
|
| 255 |
+
|│ a ┆ a_sum │|
|
| 256 |
+
|│ --- ┆ --- │|
|
| 257 |
+
|│ list[i64] ┆ i64 │|
|
| 258 |
+
|╞══════════════╪═══════╡|
|
| 259 |
+
|│ [1] ┆ 1 │|
|
| 260 |
+
|│ [3, 4, null] ┆ 7 │|
|
| 261 |
+
|└──────────────┴───────┘|
|
| 262 |
+
└────────────────────────┘
|
| 263 |
+
"""
|
| 264 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "list.sum"))
|
| 265 |
+
|
| 266 |
+
def sort(self, *, descending: bool = False, nulls_last: bool = False) -> ExprT:
|
| 267 |
+
"""Sort the lists of the expression.
|
| 268 |
+
|
| 269 |
+
Arguments:
|
| 270 |
+
descending: Sort in descending order.
|
| 271 |
+
nulls_last: Place null values last.
|
| 272 |
+
|
| 273 |
+
Examples:
|
| 274 |
+
>>> import duckdb
|
| 275 |
+
>>> import narwhals as nw
|
| 276 |
+
>>> df_native = duckdb.sql(
|
| 277 |
+
... "SELECT * FROM VALUES ([2, -1, 1]), ([3, -4, NULL]) df(a)"
|
| 278 |
+
... )
|
| 279 |
+
>>> df = nw.from_native(df_native)
|
| 280 |
+
>>> df.with_columns(a_sorted=nw.col("a").list.sort())
|
| 281 |
+
┌─────────────────────────────────┐
|
| 282 |
+
| Narwhals LazyFrame |
|
| 283 |
+
|---------------------------------|
|
| 284 |
+
|┌───────────────┬───────────────┐|
|
| 285 |
+
|│ a │ a_sorted │|
|
| 286 |
+
|│ int32[] │ int32[] │|
|
| 287 |
+
|├───────────────┼───────────────┤|
|
| 288 |
+
|│ [2, -1, 1] │ [-1, 1, 2] │|
|
| 289 |
+
|│ [3, -4, NULL] │ [NULL, -4, 3] │|
|
| 290 |
+
|└───────────────┴───────────────┘|
|
| 291 |
+
└─────────────────────────────────┘
|
| 292 |
+
"""
|
| 293 |
+
return self._expr._append_node(
|
| 294 |
+
ExprNode(
|
| 295 |
+
ExprKind.ELEMENTWISE,
|
| 296 |
+
"list.sort",
|
| 297 |
+
descending=descending,
|
| 298 |
+
nulls_last=nulls_last,
|
| 299 |
+
)
|
| 300 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/expr_name.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Callable, Generic, TypeVar
|
| 4 |
+
|
| 5 |
+
from narwhals._expression_parsing import ExprKind, ExprNode
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from narwhals.expr import Expr
|
| 9 |
+
|
| 10 |
+
ExprT = TypeVar("ExprT", bound="Expr")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ExprNameNamespace(Generic[ExprT]):
|
| 14 |
+
def __init__(self, expr: ExprT) -> None:
|
| 15 |
+
self._expr = expr
|
| 16 |
+
|
| 17 |
+
def keep(self) -> ExprT:
|
| 18 |
+
r"""Keep the original root name of the expression.
|
| 19 |
+
|
| 20 |
+
Notes:
|
| 21 |
+
For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression.
|
| 22 |
+
|
| 23 |
+
Examples:
|
| 24 |
+
>>> import pandas as pd
|
| 25 |
+
>>> import narwhals as nw
|
| 26 |
+
>>> df_native = pd.DataFrame({"foo": [1, 2], "BAR": [4, 5]})
|
| 27 |
+
>>> df = nw.from_native(df_native)
|
| 28 |
+
>>> df.select(nw.col("foo").alias("alias_for_foo").name.keep()).columns
|
| 29 |
+
['foo']
|
| 30 |
+
"""
|
| 31 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "name.keep"))
|
| 32 |
+
|
| 33 |
+
def map(self, function: Callable[[str], str]) -> ExprT:
|
| 34 |
+
r"""Rename the output of an expression by mapping a function over the root name.
|
| 35 |
+
|
| 36 |
+
Arguments:
|
| 37 |
+
function: Function that maps a root name to a new name.
|
| 38 |
+
|
| 39 |
+
Notes:
|
| 40 |
+
For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression.
|
| 41 |
+
|
| 42 |
+
Examples:
|
| 43 |
+
>>> import pandas as pd
|
| 44 |
+
>>> import narwhals as nw
|
| 45 |
+
>>> df_native = pd.DataFrame({"foo": [1, 2], "BAR": [4, 5]})
|
| 46 |
+
>>> df = nw.from_native(df_native)
|
| 47 |
+
>>> renaming_func = lambda s: s[::-1] # reverse column name
|
| 48 |
+
>>> df.select(nw.col("foo", "BAR").name.map(renaming_func)).columns
|
| 49 |
+
['oof', 'RAB']
|
| 50 |
+
"""
|
| 51 |
+
return self._expr._append_node(
|
| 52 |
+
ExprNode(ExprKind.ELEMENTWISE, "name.map", function=function)
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def prefix(self, prefix: str) -> ExprT:
|
| 56 |
+
r"""Add a prefix to the root column name of the expression.
|
| 57 |
+
|
| 58 |
+
Arguments:
|
| 59 |
+
prefix: Prefix to add to the root column name.
|
| 60 |
+
|
| 61 |
+
Notes:
|
| 62 |
+
For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression.
|
| 63 |
+
|
| 64 |
+
Examples:
|
| 65 |
+
>>> import polars as pl
|
| 66 |
+
>>> import narwhals as nw
|
| 67 |
+
>>> df_native = pl.DataFrame({"foo": [1, 2], "BAR": [4, 5]})
|
| 68 |
+
>>> df = nw.from_native(df_native)
|
| 69 |
+
>>> df.select(nw.col("foo", "BAR").name.prefix("with_prefix")).columns
|
| 70 |
+
['with_prefixfoo', 'with_prefixBAR']
|
| 71 |
+
"""
|
| 72 |
+
return self._expr._append_node(
|
| 73 |
+
ExprNode(ExprKind.ELEMENTWISE, "name.prefix", prefix=prefix)
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
def suffix(self, suffix: str) -> ExprT:
|
| 77 |
+
r"""Add a suffix to the root column name of the expression.
|
| 78 |
+
|
| 79 |
+
Arguments:
|
| 80 |
+
suffix: Suffix to add to the root column name.
|
| 81 |
+
|
| 82 |
+
Notes:
|
| 83 |
+
For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression.
|
| 84 |
+
|
| 85 |
+
Examples:
|
| 86 |
+
>>> import polars as pl
|
| 87 |
+
>>> import narwhals as nw
|
| 88 |
+
>>> df_native = pl.DataFrame({"foo": [1, 2], "BAR": [4, 5]})
|
| 89 |
+
>>> df = nw.from_native(df_native)
|
| 90 |
+
>>> df.select(nw.col("foo", "BAR").name.suffix("_with_suffix")).columns
|
| 91 |
+
['foo_with_suffix', 'BAR_with_suffix']
|
| 92 |
+
"""
|
| 93 |
+
return self._expr._append_node(
|
| 94 |
+
ExprNode(ExprKind.ELEMENTWISE, "name.suffix", suffix=suffix)
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def to_lowercase(self) -> ExprT:
|
| 98 |
+
r"""Make the root column name lowercase.
|
| 99 |
+
|
| 100 |
+
Notes:
|
| 101 |
+
For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression.
|
| 102 |
+
|
| 103 |
+
Examples:
|
| 104 |
+
>>> import pyarrow as pa
|
| 105 |
+
>>> import narwhals as nw
|
| 106 |
+
>>> df_native = pa.table({"foo": [1, 2], "BAR": [4, 5]})
|
| 107 |
+
>>> df = nw.from_native(df_native)
|
| 108 |
+
>>> df.select(nw.col("foo", "BAR").name.to_lowercase()).columns
|
| 109 |
+
['foo', 'bar']
|
| 110 |
+
"""
|
| 111 |
+
return self._expr._append_node(
|
| 112 |
+
ExprNode(ExprKind.ELEMENTWISE, "name.to_lowercase")
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def to_uppercase(self) -> ExprT:
|
| 116 |
+
r"""Make the root column name uppercase.
|
| 117 |
+
|
| 118 |
+
Notes:
|
| 119 |
+
For Polars versions prior to 1.32, this will undo any previous renaming operations on the expression.
|
| 120 |
+
|
| 121 |
+
Examples:
|
| 122 |
+
>>> import pyarrow as pa
|
| 123 |
+
>>> import narwhals as nw
|
| 124 |
+
>>> df_native = pa.table({"foo": [1, 2], "BAR": [4, 5]})
|
| 125 |
+
>>> df = nw.from_native(df_native)
|
| 126 |
+
>>> df.select(nw.col("foo", "BAR").name.to_uppercase()).columns
|
| 127 |
+
['FOO', 'BAR']
|
| 128 |
+
"""
|
| 129 |
+
return self._expr._append_node(
|
| 130 |
+
ExprNode(ExprKind.ELEMENTWISE, "name.to_uppercase")
|
| 131 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/expr_str.py
ADDED
|
@@ -0,0 +1,579 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Generic, TypeVar
|
| 4 |
+
|
| 5 |
+
from narwhals._expression_parsing import ExprKind, ExprNode
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from narwhals.expr import Expr
|
| 9 |
+
from narwhals.typing import IntoExpr
|
| 10 |
+
|
| 11 |
+
ExprT = TypeVar("ExprT", bound="Expr")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ExprStringNamespace(Generic[ExprT]):
|
| 15 |
+
def __init__(self, expr: ExprT) -> None:
|
| 16 |
+
self._expr = expr
|
| 17 |
+
|
| 18 |
+
def len_chars(self) -> ExprT:
|
| 19 |
+
r"""Return the length of each string as the number of characters.
|
| 20 |
+
|
| 21 |
+
Examples:
|
| 22 |
+
>>> import polars as pl
|
| 23 |
+
>>> import narwhals as nw
|
| 24 |
+
>>> df_native = pl.DataFrame({"words": ["foo", "345", None]})
|
| 25 |
+
>>> df = nw.from_native(df_native)
|
| 26 |
+
>>> df.with_columns(words_len=nw.col("words").str.len_chars())
|
| 27 |
+
┌─────────────────────┐
|
| 28 |
+
| Narwhals DataFrame |
|
| 29 |
+
|---------------------|
|
| 30 |
+
|shape: (3, 2) |
|
| 31 |
+
|┌───────┬───────────┐|
|
| 32 |
+
|│ words ┆ words_len │|
|
| 33 |
+
|│ --- ┆ --- │|
|
| 34 |
+
|│ str ┆ u32 │|
|
| 35 |
+
|╞═══════╪═══════════╡|
|
| 36 |
+
|│ foo ┆ 3 │|
|
| 37 |
+
|│ 345 ┆ 3 │|
|
| 38 |
+
|│ null ┆ null │|
|
| 39 |
+
|└───────┴───────────┘|
|
| 40 |
+
└─────────────────────┘
|
| 41 |
+
"""
|
| 42 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.len_chars"))
|
| 43 |
+
|
| 44 |
+
def replace(
|
| 45 |
+
self, pattern: str, value: str | IntoExpr, *, literal: bool = False, n: int = 1
|
| 46 |
+
) -> ExprT:
|
| 47 |
+
r"""Replace first matching regex/literal substring with a new string value.
|
| 48 |
+
|
| 49 |
+
Arguments:
|
| 50 |
+
pattern: A valid regular expression pattern.
|
| 51 |
+
value: String that will replace the matched substring.
|
| 52 |
+
literal: Treat `pattern` as a literal string.
|
| 53 |
+
n: Number of matches to replace.
|
| 54 |
+
|
| 55 |
+
Examples:
|
| 56 |
+
>>> import pandas as pd
|
| 57 |
+
>>> import narwhals as nw
|
| 58 |
+
>>> df_native = pd.DataFrame({"foo": ["123abc", "abc abc123"]})
|
| 59 |
+
>>> df = nw.from_native(df_native)
|
| 60 |
+
>>> df.with_columns(replaced=nw.col("foo").str.replace("abc", ""))
|
| 61 |
+
┌──────────────────────┐
|
| 62 |
+
| Narwhals DataFrame |
|
| 63 |
+
|----------------------|
|
| 64 |
+
| foo replaced|
|
| 65 |
+
|0 123abc 123|
|
| 66 |
+
|1 abc abc123 abc123|
|
| 67 |
+
└──────────────────────┘
|
| 68 |
+
"""
|
| 69 |
+
return self._expr._append_node(
|
| 70 |
+
ExprNode(
|
| 71 |
+
ExprKind.ELEMENTWISE,
|
| 72 |
+
"str.replace",
|
| 73 |
+
exprs=(value,),
|
| 74 |
+
pattern=pattern,
|
| 75 |
+
literal=literal,
|
| 76 |
+
n=n,
|
| 77 |
+
str_as_lit=True,
|
| 78 |
+
)
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
def replace_all(
|
| 82 |
+
self, pattern: str, value: IntoExpr, *, literal: bool = False
|
| 83 |
+
) -> ExprT:
|
| 84 |
+
r"""Replace all matching regex/literal substring with a new string value.
|
| 85 |
+
|
| 86 |
+
Arguments:
|
| 87 |
+
pattern: A valid regular expression pattern.
|
| 88 |
+
value: String that will replace the matched substring.
|
| 89 |
+
literal: Treat `pattern` as a literal string.
|
| 90 |
+
|
| 91 |
+
Examples:
|
| 92 |
+
>>> import pandas as pd
|
| 93 |
+
>>> import narwhals as nw
|
| 94 |
+
>>> df_native = pd.DataFrame({"foo": ["123abc", "abc abc123"]})
|
| 95 |
+
>>> df = nw.from_native(df_native)
|
| 96 |
+
>>> df.with_columns(replaced=nw.col("foo").str.replace_all("abc", ""))
|
| 97 |
+
┌──────────────────────┐
|
| 98 |
+
| Narwhals DataFrame |
|
| 99 |
+
|----------------------|
|
| 100 |
+
| foo replaced|
|
| 101 |
+
|0 123abc 123|
|
| 102 |
+
|1 abc abc123 123|
|
| 103 |
+
└──────────────────────┘
|
| 104 |
+
"""
|
| 105 |
+
return self._expr._append_node(
|
| 106 |
+
ExprNode(
|
| 107 |
+
ExprKind.ELEMENTWISE,
|
| 108 |
+
"str.replace_all",
|
| 109 |
+
exprs=(value,),
|
| 110 |
+
pattern=pattern,
|
| 111 |
+
literal=literal,
|
| 112 |
+
str_as_lit=True,
|
| 113 |
+
)
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def strip_chars(self, characters: str | None = None) -> ExprT:
|
| 117 |
+
r"""Remove leading and trailing characters.
|
| 118 |
+
|
| 119 |
+
Arguments:
|
| 120 |
+
characters: The set of characters to be removed. All combinations of this
|
| 121 |
+
set of characters will be stripped from the start and end of the string.
|
| 122 |
+
If set to None (default), all leading and trailing whitespace is removed
|
| 123 |
+
instead.
|
| 124 |
+
|
| 125 |
+
Examples:
|
| 126 |
+
>>> import polars as pl
|
| 127 |
+
>>> import narwhals as nw
|
| 128 |
+
>>> df_native = pl.DataFrame({"fruits": ["apple", "\nmango"]})
|
| 129 |
+
>>> df = nw.from_native(df_native)
|
| 130 |
+
>>> df.with_columns(stripped=nw.col("fruits").str.strip_chars()).to_dict(
|
| 131 |
+
... as_series=False
|
| 132 |
+
... )
|
| 133 |
+
{'fruits': ['apple', '\nmango'], 'stripped': ['apple', 'mango']}
|
| 134 |
+
"""
|
| 135 |
+
return self._expr._append_node(
|
| 136 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.strip_chars", characters=characters)
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def starts_with(self, prefix: str) -> ExprT:
|
| 140 |
+
r"""Check if string values start with a substring.
|
| 141 |
+
|
| 142 |
+
Arguments:
|
| 143 |
+
prefix: prefix substring
|
| 144 |
+
|
| 145 |
+
Examples:
|
| 146 |
+
>>> import pandas as pd
|
| 147 |
+
>>> import narwhals as nw
|
| 148 |
+
>>> df_native = pd.DataFrame({"fruits": ["apple", "mango", None]})
|
| 149 |
+
>>> df = nw.from_native(df_native)
|
| 150 |
+
>>> df.with_columns(has_prefix=nw.col("fruits").str.starts_with("app"))
|
| 151 |
+
┌────────────────────┐
|
| 152 |
+
| Narwhals DataFrame |
|
| 153 |
+
|--------------------|
|
| 154 |
+
| fruits has_prefix|
|
| 155 |
+
|0 apple True|
|
| 156 |
+
|1 mango False|
|
| 157 |
+
|2 NaN False|
|
| 158 |
+
└────────────────────┘
|
| 159 |
+
"""
|
| 160 |
+
return self._expr._append_node(
|
| 161 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.starts_with", prefix=prefix)
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def ends_with(self, suffix: str) -> ExprT:
|
| 165 |
+
r"""Check if string values end with a substring.
|
| 166 |
+
|
| 167 |
+
Arguments:
|
| 168 |
+
suffix: suffix substring
|
| 169 |
+
|
| 170 |
+
Examples:
|
| 171 |
+
>>> import pandas as pd
|
| 172 |
+
>>> import narwhals as nw
|
| 173 |
+
>>> df_native = pd.DataFrame({"fruits": ["apple", "mango", None]})
|
| 174 |
+
>>> df = nw.from_native(df_native)
|
| 175 |
+
>>> df.with_columns(has_suffix=nw.col("fruits").str.ends_with("ngo"))
|
| 176 |
+
┌────────────────────┐
|
| 177 |
+
| Narwhals DataFrame |
|
| 178 |
+
|--------------------|
|
| 179 |
+
| fruits has_suffix|
|
| 180 |
+
|0 apple False|
|
| 181 |
+
|1 mango True|
|
| 182 |
+
|2 NaN False|
|
| 183 |
+
└────────────────────┘
|
| 184 |
+
"""
|
| 185 |
+
return self._expr._append_node(
|
| 186 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.ends_with", suffix=suffix)
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
def contains(self, pattern: str | IntoExpr, *, literal: bool = False) -> ExprT:
|
| 190 |
+
r"""Check if string contains a substring that matches a pattern.
|
| 191 |
+
|
| 192 |
+
Arguments:
|
| 193 |
+
pattern: A Character sequence, valid regular expression pattern, or another
|
| 194 |
+
Expr.
|
| 195 |
+
literal: If True, treats the pattern as a literal string.
|
| 196 |
+
If False, assumes the pattern is a regular expression.
|
| 197 |
+
|
| 198 |
+
Warning:
|
| 199 |
+
Passing an expression as `pattern` is only supported by DuckDB, Ibis, Polars,
|
| 200 |
+
PySpark and SQLFrame. Other backends, such as pandas and PyArrow, will raise
|
| 201 |
+
a `TypeError`.
|
| 202 |
+
|
| 203 |
+
Examples:
|
| 204 |
+
>>> import pyarrow as pa
|
| 205 |
+
>>> import narwhals as nw
|
| 206 |
+
>>> df_native = pa.table({"pets": ["cat", "dog", "rabbit and parrot"]})
|
| 207 |
+
>>> df = nw.from_native(df_native)
|
| 208 |
+
>>> df.with_columns(
|
| 209 |
+
... default_match=nw.col("pets").str.contains("cat|parrot"),
|
| 210 |
+
... case_insensitive_match=nw.col("pets").str.contains("cat|(?i)parrot"),
|
| 211 |
+
... ).to_native()
|
| 212 |
+
pyarrow.Table
|
| 213 |
+
pets: string
|
| 214 |
+
default_match: bool
|
| 215 |
+
case_insensitive_match: bool
|
| 216 |
+
----
|
| 217 |
+
pets: [["cat","dog","rabbit and parrot"]]
|
| 218 |
+
default_match: [[true,false,true]]
|
| 219 |
+
case_insensitive_match: [[true,false,true]]
|
| 220 |
+
"""
|
| 221 |
+
return self._expr._append_node(
|
| 222 |
+
ExprNode(
|
| 223 |
+
ExprKind.ELEMENTWISE,
|
| 224 |
+
"str.contains",
|
| 225 |
+
exprs=(pattern,),
|
| 226 |
+
literal=literal,
|
| 227 |
+
str_as_lit=True,
|
| 228 |
+
)
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
def slice(self, offset: int, length: int | None = None) -> ExprT:
|
| 232 |
+
r"""Create subslices of the string values of an expression.
|
| 233 |
+
|
| 234 |
+
Arguments:
|
| 235 |
+
offset: Start index. Negative indexing is supported.
|
| 236 |
+
length: Length of the slice. If set to `None` (default), the slice is taken to the
|
| 237 |
+
end of the string.
|
| 238 |
+
|
| 239 |
+
Examples:
|
| 240 |
+
>>> import pandas as pd
|
| 241 |
+
>>> import narwhals as nw
|
| 242 |
+
>>> df_native = pd.DataFrame({"s": ["pear", None, "papaya"]})
|
| 243 |
+
>>> df = nw.from_native(df_native)
|
| 244 |
+
>>> df.with_columns(s_sliced=nw.col("s").str.slice(4, length=3))
|
| 245 |
+
┌──────────────────┐
|
| 246 |
+
|Narwhals DataFrame|
|
| 247 |
+
|------------------|
|
| 248 |
+
| s s_sliced|
|
| 249 |
+
|0 pear |
|
| 250 |
+
|1 NaN NaN|
|
| 251 |
+
|2 papaya ya|
|
| 252 |
+
└──────────────────┘
|
| 253 |
+
"""
|
| 254 |
+
return self._expr._append_node(
|
| 255 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=offset, length=length)
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
def split(self, by: str) -> ExprT:
|
| 259 |
+
r"""Split the string values of an expression by a substring.
|
| 260 |
+
|
| 261 |
+
Arguments:
|
| 262 |
+
by: Substring to split by.
|
| 263 |
+
|
| 264 |
+
Examples:
|
| 265 |
+
>>> import polars as pl
|
| 266 |
+
>>> import narwhals as nw
|
| 267 |
+
>>> df_native = pl.DataFrame({"s": ["foo bar", "foo_bar"]})
|
| 268 |
+
>>> df = nw.from_native(df_native)
|
| 269 |
+
>>> df.with_columns(nw.col("s").str.split("_").alias("s_split"))
|
| 270 |
+
┌────────────────────────────┐
|
| 271 |
+
| Narwhals DataFrame |
|
| 272 |
+
|----------------------------|
|
| 273 |
+
|shape: (2, 2) |
|
| 274 |
+
|┌─────────┬────────────────┐|
|
| 275 |
+
|│ s ┆ s_split │|
|
| 276 |
+
|│ --- ┆ --- │|
|
| 277 |
+
|│ str ┆ list[str] │|
|
| 278 |
+
|╞═════════╪════════════════╡|
|
| 279 |
+
|│ foo bar ┆ ["foo bar"] │|
|
| 280 |
+
|│ foo_bar ┆ ["foo", "bar"] │|
|
| 281 |
+
|└─────────┴────────────────┘|
|
| 282 |
+
└────────────────────────────┘
|
| 283 |
+
"""
|
| 284 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.split", by=by))
|
| 285 |
+
|
| 286 |
+
def head(self, n: int = 5) -> ExprT:
|
| 287 |
+
r"""Take the first n elements of each string.
|
| 288 |
+
|
| 289 |
+
Arguments:
|
| 290 |
+
n: Number of elements to take. Negative indexing is **not** supported.
|
| 291 |
+
|
| 292 |
+
Notes:
|
| 293 |
+
If the length of the string has fewer than `n` characters, the full string is returned.
|
| 294 |
+
|
| 295 |
+
Examples:
|
| 296 |
+
>>> import pyarrow as pa
|
| 297 |
+
>>> import narwhals as nw
|
| 298 |
+
>>> df_native = pa.table({"lyrics": ["taata", "taatatata", "zukkyun"]})
|
| 299 |
+
>>> df = nw.from_native(df_native)
|
| 300 |
+
>>> df.with_columns(lyrics_head=nw.col("lyrics").str.head()).to_native()
|
| 301 |
+
pyarrow.Table
|
| 302 |
+
lyrics: string
|
| 303 |
+
lyrics_head: string
|
| 304 |
+
----
|
| 305 |
+
lyrics: [["taata","taatatata","zukkyun"]]
|
| 306 |
+
lyrics_head: [["taata","taata","zukky"]]
|
| 307 |
+
"""
|
| 308 |
+
return self._expr._append_node(
|
| 309 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=0, length=n)
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
def tail(self, n: int = 5) -> ExprT:
|
| 313 |
+
r"""Take the last n elements of each string.
|
| 314 |
+
|
| 315 |
+
Arguments:
|
| 316 |
+
n: Number of elements to take. Negative indexing is **not** supported.
|
| 317 |
+
|
| 318 |
+
Notes:
|
| 319 |
+
If the length of the string has fewer than `n` characters, the full string is returned.
|
| 320 |
+
|
| 321 |
+
Examples:
|
| 322 |
+
>>> import pyarrow as pa
|
| 323 |
+
>>> import narwhals as nw
|
| 324 |
+
>>> df_native = pa.table({"lyrics": ["taata", "taatatata", "zukkyun"]})
|
| 325 |
+
>>> df = nw.from_native(df_native)
|
| 326 |
+
>>> df.with_columns(lyrics_tail=nw.col("lyrics").str.tail()).to_native()
|
| 327 |
+
pyarrow.Table
|
| 328 |
+
lyrics: string
|
| 329 |
+
lyrics_tail: string
|
| 330 |
+
----
|
| 331 |
+
lyrics: [["taata","taatatata","zukkyun"]]
|
| 332 |
+
lyrics_tail: [["taata","atata","kkyun"]]
|
| 333 |
+
"""
|
| 334 |
+
return self._expr._append_node(
|
| 335 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.slice", offset=-n, length=None)
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
def to_datetime(self, format: str | None = None) -> ExprT:
|
| 339 |
+
"""Convert to Datetime dtype.
|
| 340 |
+
|
| 341 |
+
Notes:
|
| 342 |
+
- pandas defaults to nanosecond time unit, Polars to microsecond.
|
| 343 |
+
Prior to pandas 2.0, nanoseconds were the only time unit supported
|
| 344 |
+
in pandas, with no ability to set any other one. The ability to
|
| 345 |
+
set the time unit in pandas, if the version permits, will arrive.
|
| 346 |
+
- timezone-aware strings are all converted to and parsed as UTC.
|
| 347 |
+
|
| 348 |
+
Warning:
|
| 349 |
+
As different backends auto-infer format in different ways, if `format=None`
|
| 350 |
+
there is no guarantee that the result will be equal.
|
| 351 |
+
|
| 352 |
+
Arguments:
|
| 353 |
+
format: Format to use for conversion. If set to None (default), the format is
|
| 354 |
+
inferred from the data.
|
| 355 |
+
|
| 356 |
+
Examples:
|
| 357 |
+
>>> import polars as pl
|
| 358 |
+
>>> import narwhals as nw
|
| 359 |
+
>>> df_native = pl.DataFrame({"a": ["2020-01-01", "2020-01-02"]})
|
| 360 |
+
>>> df = nw.from_native(df_native)
|
| 361 |
+
>>> df.select(nw.col("a").str.to_datetime(format="%Y-%m-%d"))
|
| 362 |
+
┌───────────────────────┐
|
| 363 |
+
| Narwhals DataFrame |
|
| 364 |
+
|-----------------------|
|
| 365 |
+
|shape: (2, 1) |
|
| 366 |
+
|┌────────────────────���┐|
|
| 367 |
+
|│ a │|
|
| 368 |
+
|│ --- │|
|
| 369 |
+
|│ datetime[μs] │|
|
| 370 |
+
|╞═════════════════════╡|
|
| 371 |
+
|│ 2020-01-01 00:00:00 │|
|
| 372 |
+
|│ 2020-01-02 00:00:00 │|
|
| 373 |
+
|└─────────────────────┘|
|
| 374 |
+
└───────────────────────┘
|
| 375 |
+
"""
|
| 376 |
+
return self._expr._append_node(
|
| 377 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.to_datetime", format=format)
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
def to_date(self, format: str | None = None) -> ExprT:
|
| 381 |
+
"""Convert to date dtype.
|
| 382 |
+
|
| 383 |
+
Warning:
|
| 384 |
+
As different backends auto-infer format in different ways, if `format=None`
|
| 385 |
+
there is no guarantee that the result will be equal.
|
| 386 |
+
|
| 387 |
+
Arguments:
|
| 388 |
+
format: Format to use for conversion. If set to None (default), the format is inferred from the data.
|
| 389 |
+
|
| 390 |
+
Examples:
|
| 391 |
+
>>> import pyarrow as pa
|
| 392 |
+
>>> import narwhals as nw
|
| 393 |
+
>>> df_native = pa.table({"a": ["2020-01-01", "2020-01-02"]})
|
| 394 |
+
>>> df = nw.from_native(df_native)
|
| 395 |
+
>>> df.select(nw.col("a").str.to_date(format="%Y-%m-%d"))
|
| 396 |
+
┌────────────────────────────┐
|
| 397 |
+
| Narwhals DataFrame |
|
| 398 |
+
|----------------------------|
|
| 399 |
+
|pyarrow.Table |
|
| 400 |
+
|a: date32[day] |
|
| 401 |
+
|---- |
|
| 402 |
+
|a: [[2020-01-01,2020-01-02]]|
|
| 403 |
+
└────────────────────────────┘
|
| 404 |
+
"""
|
| 405 |
+
return self._expr._append_node(
|
| 406 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.to_date", format=format)
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
def to_uppercase(self) -> ExprT:
|
| 410 |
+
r"""Transform string to uppercase variant.
|
| 411 |
+
|
| 412 |
+
Notes:
|
| 413 |
+
The PyArrow backend will convert 'ß' to 'ẞ' instead of 'SS'.
|
| 414 |
+
For more info see [the related issue](https://github.com/apache/arrow/issues/34599).
|
| 415 |
+
There may be other unicode-edge-case-related variations across implementations.
|
| 416 |
+
|
| 417 |
+
Examples:
|
| 418 |
+
>>> import pandas as pd
|
| 419 |
+
>>> import narwhals as nw
|
| 420 |
+
>>> df_native = pd.DataFrame({"fruits": ["apple", None]})
|
| 421 |
+
>>> df = nw.from_native(df_native)
|
| 422 |
+
>>> df.with_columns(upper_col=nw.col("fruits").str.to_uppercase())
|
| 423 |
+
┌──────────────────┐
|
| 424 |
+
|Narwhals DataFrame|
|
| 425 |
+
|------------------|
|
| 426 |
+
| fruits upper_col|
|
| 427 |
+
|0 apple APPLE|
|
| 428 |
+
|1 NaN NaN|
|
| 429 |
+
└──────────────────┘
|
| 430 |
+
"""
|
| 431 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_uppercase"))
|
| 432 |
+
|
| 433 |
+
def to_lowercase(self) -> ExprT:
|
| 434 |
+
r"""Transform string to lowercase variant.
|
| 435 |
+
|
| 436 |
+
Examples:
|
| 437 |
+
>>> import pandas as pd
|
| 438 |
+
>>> import narwhals as nw
|
| 439 |
+
>>> df_native = pd.DataFrame({"fruits": ["APPLE", None]})
|
| 440 |
+
>>> df = nw.from_native(df_native)
|
| 441 |
+
>>> df.with_columns(lower_col=nw.col("fruits").str.to_lowercase())
|
| 442 |
+
┌──────────────────┐
|
| 443 |
+
|Narwhals DataFrame|
|
| 444 |
+
|------------------|
|
| 445 |
+
| fruits lower_col|
|
| 446 |
+
|0 APPLE apple|
|
| 447 |
+
|1 NaN NaN|
|
| 448 |
+
└──────────────────┘
|
| 449 |
+
"""
|
| 450 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_lowercase"))
|
| 451 |
+
|
| 452 |
+
def to_titlecase(self) -> ExprT:
|
| 453 |
+
"""Modify strings to their titlecase equivalent.
|
| 454 |
+
|
| 455 |
+
Notes:
|
| 456 |
+
This is a form of case transform where the first letter of each word is
|
| 457 |
+
capitalized, with the rest of the word in lowercase.
|
| 458 |
+
|
| 459 |
+
Word boundaries are defined by non-**alphabetic** characters, matching the
|
| 460 |
+
behavior of [`str.title`](https://docs.python.org/3/library/stdtypes.html#str.title)
|
| 461 |
+
|
| 462 |
+
Examples:
|
| 463 |
+
>>> import polars as pl
|
| 464 |
+
>>> import narwhals as nw
|
| 465 |
+
>>> df_native = pl.DataFrame(
|
| 466 |
+
... {
|
| 467 |
+
... "quotes": [
|
| 468 |
+
... "'e.t. phone home'",
|
| 469 |
+
... "you talkin' to me?",
|
| 470 |
+
... "to infinity,and BEYOND!",
|
| 471 |
+
... ]
|
| 472 |
+
... }
|
| 473 |
+
... )
|
| 474 |
+
>>> df = nw.from_native(df_native)
|
| 475 |
+
>>> df.with_columns(quotes_title=nw.col("quotes").str.to_titlecase())
|
| 476 |
+
┌─────────────────────────────────────────────────────┐
|
| 477 |
+
| Narwhals DataFrame |
|
| 478 |
+
|-----------------------------------------------------|
|
| 479 |
+
|shape: (3, 2) |
|
| 480 |
+
|┌─────────────────────────┬─────────────────────────┐|
|
| 481 |
+
|│ quotes ┆ quotes_title │|
|
| 482 |
+
|│ --- ┆ --- │|
|
| 483 |
+
|│ str ┆ str │|
|
| 484 |
+
|╞═════════════════════════╪═════════════════════════╡|
|
| 485 |
+
|│ 'e.t. phone home' ┆ 'E.T. Phone Home' │|
|
| 486 |
+
|│ you talkin' to me? ┆ You Talkin' To Me? │|
|
| 487 |
+
|│ to infinity,and BEYOND! ┆ To Infinity,And Beyond! │|
|
| 488 |
+
|└─────────────────────────┴─────────────────────────┘|
|
| 489 |
+
└─────────────────────────────────────────────────────┘
|
| 490 |
+
"""
|
| 491 |
+
return self._expr._append_node(ExprNode(ExprKind.ELEMENTWISE, "str.to_titlecase"))
|
| 492 |
+
|
| 493 |
+
def zfill(self, width: int) -> ExprT:
|
| 494 |
+
"""Transform string to zero-padded variant.
|
| 495 |
+
|
| 496 |
+
Arguments:
|
| 497 |
+
width: The desired length of the string after padding. If the length of the
|
| 498 |
+
string is greater than `width`, no padding is applied.
|
| 499 |
+
If `width` is less than 0, no padding is applied.
|
| 500 |
+
|
| 501 |
+
Examples:
|
| 502 |
+
>>> import pandas as pd
|
| 503 |
+
>>> import narwhals as nw
|
| 504 |
+
>>> df_native = pd.DataFrame({"digits": ["+1", "-1", "1", None]})
|
| 505 |
+
>>> df = nw.from_native(df_native)
|
| 506 |
+
>>> df.with_columns(zfill_col=nw.col("digits").str.zfill(3))
|
| 507 |
+
┌──────────────────┐
|
| 508 |
+
|Narwhals DataFrame|
|
| 509 |
+
|------------------|
|
| 510 |
+
| digits zfill_col|
|
| 511 |
+
|0 +1 +01|
|
| 512 |
+
|1 -1 -01|
|
| 513 |
+
|2 1 001|
|
| 514 |
+
|3 NaN NaN|
|
| 515 |
+
└──────────────────┘
|
| 516 |
+
"""
|
| 517 |
+
return self._expr._append_node(
|
| 518 |
+
ExprNode(ExprKind.ELEMENTWISE, "str.zfill", width=width)
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
def pad_start(self, length: int, fill_char: str = " ") -> ExprT:
|
| 522 |
+
"""Pad the start of the string until it reaches the given length.
|
| 523 |
+
|
| 524 |
+
Arguments:
|
| 525 |
+
length: Pad the string until it reaches this length. Strings with
|
| 526 |
+
length equal to or greater than this value are returned as-is.
|
| 527 |
+
fill_char: The character to pad the string with.
|
| 528 |
+
|
| 529 |
+
Examples:
|
| 530 |
+
>>> import pandas as pd
|
| 531 |
+
>>> import narwhals as nw
|
| 532 |
+
>>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]})
|
| 533 |
+
>>> df = nw.from_native(df_native)
|
| 534 |
+
>>> df.with_columns(padded=nw.col("a").str.pad_start(8, "*"))
|
| 535 |
+
┌─────────────────────────────┐
|
| 536 |
+
| Narwhals DataFrame |
|
| 537 |
+
|-----------------------------|
|
| 538 |
+
| a padded|
|
| 539 |
+
|0 cow *****cow|
|
| 540 |
+
|1 monkey **monkey|
|
| 541 |
+
|2 hippopotamus hippopotamus|
|
| 542 |
+
|3 NaN NaN|
|
| 543 |
+
└─────────────────────────────┘
|
| 544 |
+
"""
|
| 545 |
+
return self._expr._append_node(
|
| 546 |
+
ExprNode(
|
| 547 |
+
ExprKind.ELEMENTWISE, "str.pad_start", length=length, fill_char=fill_char
|
| 548 |
+
)
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
def pad_end(self, length: int, fill_char: str = " ") -> ExprT:
|
| 552 |
+
"""Pad the end of the string until it reaches the given length.
|
| 553 |
+
|
| 554 |
+
Arguments:
|
| 555 |
+
length: Pad the string until it reaches this length. Strings with
|
| 556 |
+
length equal to or greater than this value are returned as-is.
|
| 557 |
+
fill_char: The character to pad the string with.
|
| 558 |
+
|
| 559 |
+
Examples:
|
| 560 |
+
>>> import pandas as pd
|
| 561 |
+
>>> import narwhals as nw
|
| 562 |
+
>>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]})
|
| 563 |
+
>>> df = nw.from_native(df_native)
|
| 564 |
+
>>> df.with_columns(padded=nw.col("a").str.pad_end(8, "*"))
|
| 565 |
+
┌─────────────────────────────┐
|
| 566 |
+
| Narwhals DataFrame |
|
| 567 |
+
|-----------------------------|
|
| 568 |
+
| a padded|
|
| 569 |
+
|0 cow cow*****|
|
| 570 |
+
|1 monkey monkey**|
|
| 571 |
+
|2 hippopotamus hippopotamus|
|
| 572 |
+
|3 NaN NaN|
|
| 573 |
+
└─────���───────────────────────┘
|
| 574 |
+
"""
|
| 575 |
+
return self._expr._append_node(
|
| 576 |
+
ExprNode(
|
| 577 |
+
ExprKind.ELEMENTWISE, "str.pad_end", length=length, fill_char=fill_char
|
| 578 |
+
)
|
| 579 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/expr_struct.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Generic, TypeVar
|
| 4 |
+
|
| 5 |
+
from narwhals._expression_parsing import ExprKind, ExprNode
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from narwhals.expr import Expr
|
| 9 |
+
|
| 10 |
+
ExprT = TypeVar("ExprT", bound="Expr")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ExprStructNamespace(Generic[ExprT]):
|
| 14 |
+
def __init__(self, expr: ExprT) -> None:
|
| 15 |
+
self._expr = expr
|
| 16 |
+
|
| 17 |
+
def field(self, name: str) -> ExprT:
|
| 18 |
+
r"""Retrieve a Struct field as a new expression.
|
| 19 |
+
|
| 20 |
+
Arguments:
|
| 21 |
+
name: Name of the struct field to retrieve.
|
| 22 |
+
|
| 23 |
+
Examples:
|
| 24 |
+
>>> import polars as pl
|
| 25 |
+
>>> import narwhals as nw
|
| 26 |
+
>>> df_native = pl.DataFrame(
|
| 27 |
+
... {"user": [{"id": "0", "name": "john"}, {"id": "1", "name": "jane"}]}
|
| 28 |
+
... )
|
| 29 |
+
>>> df = nw.from_native(df_native)
|
| 30 |
+
>>> df.with_columns(name=nw.col("user").struct.field("name"))
|
| 31 |
+
┌───────────────────────┐
|
| 32 |
+
| Narwhals DataFrame |
|
| 33 |
+
|-----------------------|
|
| 34 |
+
|shape: (2, 2) |
|
| 35 |
+
|┌──────────────┬──────┐|
|
| 36 |
+
|│ user ┆ name │|
|
| 37 |
+
|│ --- ┆ --- │|
|
| 38 |
+
|│ struct[2] ┆ str │|
|
| 39 |
+
|╞══════════════╪══════╡|
|
| 40 |
+
|│ {"0","john"} ┆ john │|
|
| 41 |
+
|│ {"1","jane"} ┆ jane │|
|
| 42 |
+
|└──────────────┴──────┘|
|
| 43 |
+
└───────────────────────┘
|
| 44 |
+
"""
|
| 45 |
+
return self._expr._append_node(
|
| 46 |
+
ExprNode(ExprKind.ELEMENTWISE, "struct.field", name=name)
|
| 47 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/functions.py
ADDED
|
@@ -0,0 +1,1829 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import platform
|
| 4 |
+
import sys
|
| 5 |
+
from collections.abc import Iterable, Mapping, Sequence
|
| 6 |
+
from typing import TYPE_CHECKING, Any
|
| 7 |
+
|
| 8 |
+
from narwhals._expression_parsing import ExprKind, ExprNode, is_expr, is_series
|
| 9 |
+
from narwhals._utils import (
|
| 10 |
+
Implementation,
|
| 11 |
+
Version,
|
| 12 |
+
deprecate_native_namespace,
|
| 13 |
+
flatten,
|
| 14 |
+
is_eager_allowed,
|
| 15 |
+
is_nested_literal,
|
| 16 |
+
is_sequence_but_not_str,
|
| 17 |
+
normalize_path,
|
| 18 |
+
supports_arrow_c_stream,
|
| 19 |
+
validate_laziness,
|
| 20 |
+
)
|
| 21 |
+
from narwhals.dependencies import (
|
| 22 |
+
is_narwhals_series,
|
| 23 |
+
is_numpy_array,
|
| 24 |
+
is_numpy_array_2d,
|
| 25 |
+
is_pyarrow_table,
|
| 26 |
+
)
|
| 27 |
+
from narwhals.exceptions import InvalidOperationError
|
| 28 |
+
from narwhals.expr import Expr
|
| 29 |
+
from narwhals.translate import from_native, to_native
|
| 30 |
+
|
| 31 |
+
if TYPE_CHECKING:
|
| 32 |
+
from types import ModuleType
|
| 33 |
+
|
| 34 |
+
from typing_extensions import TypeAlias, TypeIs
|
| 35 |
+
|
| 36 |
+
from narwhals._native import NativeDataFrame, NativeLazyFrame, NativeSeries
|
| 37 |
+
from narwhals._translate import IntoArrowTable
|
| 38 |
+
from narwhals._typing import Backend, EagerAllowed, IntoBackend
|
| 39 |
+
from narwhals.dataframe import DataFrame, LazyFrame
|
| 40 |
+
from narwhals.dtypes import DType
|
| 41 |
+
from narwhals.series import Series
|
| 42 |
+
from narwhals.typing import (
|
| 43 |
+
ConcatMethod,
|
| 44 |
+
CorrelationMethod,
|
| 45 |
+
FileSource,
|
| 46 |
+
FrameT,
|
| 47 |
+
IntoDType,
|
| 48 |
+
IntoExpr,
|
| 49 |
+
IntoSchema,
|
| 50 |
+
NonNestedLiteral,
|
| 51 |
+
PythonLiteral,
|
| 52 |
+
_2DArray,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
_IntoSchema: TypeAlias = "IntoSchema | Sequence[str] | None"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def concat(items: Iterable[FrameT], *, how: ConcatMethod = "vertical") -> FrameT:
|
| 59 |
+
"""Concatenate multiple DataFrames, LazyFrames into a single entity.
|
| 60 |
+
|
| 61 |
+
Arguments:
|
| 62 |
+
items: DataFrames, LazyFrames to concatenate.
|
| 63 |
+
how: concatenating strategy
|
| 64 |
+
|
| 65 |
+
- vertical: Concatenate vertically. Column names must match.
|
| 66 |
+
- horizontal: Concatenate horizontally. If lengths don't match, then
|
| 67 |
+
missing rows are filled with null values. This is only supported
|
| 68 |
+
when all inputs are (eager) DataFrames.
|
| 69 |
+
- diagonal: Finds a union between the column schemas and fills missing column
|
| 70 |
+
values with null.
|
| 71 |
+
|
| 72 |
+
Raises:
|
| 73 |
+
TypeError: The items to concatenate should either all be eager, or all lazy
|
| 74 |
+
|
| 75 |
+
Examples:
|
| 76 |
+
Let's take an example of vertical concatenation:
|
| 77 |
+
|
| 78 |
+
>>> import pandas as pd
|
| 79 |
+
>>> import polars as pl
|
| 80 |
+
>>> import pyarrow as pa
|
| 81 |
+
>>> import narwhals as nw
|
| 82 |
+
|
| 83 |
+
Let's look at one case a for vertical concatenation (pandas backed):
|
| 84 |
+
|
| 85 |
+
>>> df_pd_1 = nw.from_native(pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}))
|
| 86 |
+
>>> df_pd_2 = nw.from_native(pd.DataFrame({"a": [5, 2], "b": [1, 4]}))
|
| 87 |
+
>>> nw.concat([df_pd_1, df_pd_2], how="vertical")
|
| 88 |
+
┌──────────────────┐
|
| 89 |
+
|Narwhals DataFrame|
|
| 90 |
+
|------------------|
|
| 91 |
+
| a b |
|
| 92 |
+
| 0 1 4 |
|
| 93 |
+
| 1 2 5 |
|
| 94 |
+
| 2 3 6 |
|
| 95 |
+
| 0 5 1 |
|
| 96 |
+
| 1 2 4 |
|
| 97 |
+
└──────────────────┘
|
| 98 |
+
|
| 99 |
+
Let's look at one case a for horizontal concatenation (polars backed):
|
| 100 |
+
|
| 101 |
+
>>> df_pl_1 = nw.from_native(pl.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}))
|
| 102 |
+
>>> df_pl_2 = nw.from_native(pl.DataFrame({"c": [5, 2], "d": [1, 4]}))
|
| 103 |
+
>>> nw.concat([df_pl_1, df_pl_2], how="horizontal")
|
| 104 |
+
┌───────────────────────────┐
|
| 105 |
+
| Narwhals DataFrame |
|
| 106 |
+
|---------------------------|
|
| 107 |
+
|shape: (3, 4) |
|
| 108 |
+
|┌─────┬─────┬──────┬──────┐|
|
| 109 |
+
|│ a ┆ b ┆ c ┆ d │|
|
| 110 |
+
|│ --- ┆ --- ┆ --- ┆ --- │|
|
| 111 |
+
|│ i64 ┆ i64 ┆ i64 ┆ i64 │|
|
| 112 |
+
|╞═════╪═════╪══════╪══════╡|
|
| 113 |
+
|│ 1 ┆ 4 ┆ 5 ┆ 1 │|
|
| 114 |
+
|│ 2 ┆ 5 ┆ 2 ┆ 4 │|
|
| 115 |
+
|│ 3 ┆ 6 ┆ null ┆ null │|
|
| 116 |
+
|└─────┴─────┴──────┴──────┘|
|
| 117 |
+
└───────────────────────────┘
|
| 118 |
+
|
| 119 |
+
Let's look at one case a for diagonal concatenation (pyarrow backed):
|
| 120 |
+
|
| 121 |
+
>>> df_pa_1 = nw.from_native(pa.table({"a": [1, 2], "b": [3.5, 4.5]}))
|
| 122 |
+
>>> df_pa_2 = nw.from_native(pa.table({"a": [3, 4], "z": ["x", "y"]}))
|
| 123 |
+
>>> nw.concat([df_pa_1, df_pa_2], how="diagonal")
|
| 124 |
+
┌──────────────────────────┐
|
| 125 |
+
| Narwhals DataFrame |
|
| 126 |
+
|--------------------------|
|
| 127 |
+
|pyarrow.Table |
|
| 128 |
+
|a: int64 |
|
| 129 |
+
|b: double |
|
| 130 |
+
|z: string |
|
| 131 |
+
|---- |
|
| 132 |
+
|a: [[1,2],[3,4]] |
|
| 133 |
+
|b: [[3.5,4.5],[null,null]]|
|
| 134 |
+
|z: [[null,null],["x","y"]]|
|
| 135 |
+
└──────────────────────────┘
|
| 136 |
+
"""
|
| 137 |
+
from narwhals.dependencies import is_narwhals_lazyframe
|
| 138 |
+
|
| 139 |
+
if not items:
|
| 140 |
+
msg = "No items to concatenate."
|
| 141 |
+
raise ValueError(msg)
|
| 142 |
+
items = tuple(items)
|
| 143 |
+
validate_laziness(items)
|
| 144 |
+
if how not in {"horizontal", "vertical", "diagonal"}: # pragma: no cover
|
| 145 |
+
msg = "Only vertical, horizontal and diagonal concatenations are supported."
|
| 146 |
+
raise NotImplementedError(msg)
|
| 147 |
+
first_item = items[0]
|
| 148 |
+
if is_narwhals_lazyframe(first_item) and how == "horizontal":
|
| 149 |
+
msg = (
|
| 150 |
+
"Horizontal concatenation is not supported for LazyFrames.\n\n"
|
| 151 |
+
"Hint: you may want to use `join` instead."
|
| 152 |
+
)
|
| 153 |
+
raise InvalidOperationError(msg)
|
| 154 |
+
plx = first_item.__narwhals_namespace__()
|
| 155 |
+
return first_item._with_compliant(
|
| 156 |
+
plx.concat([df._compliant_frame for df in items], how=how)
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def new_series(
|
| 161 |
+
name: str,
|
| 162 |
+
values: Any,
|
| 163 |
+
dtype: IntoDType | None = None,
|
| 164 |
+
*,
|
| 165 |
+
backend: IntoBackend[EagerAllowed],
|
| 166 |
+
) -> Series[Any]:
|
| 167 |
+
"""Instantiate Narwhals Series from iterable (e.g. list or array).
|
| 168 |
+
|
| 169 |
+
Arguments:
|
| 170 |
+
name: Name of resulting Series.
|
| 171 |
+
values: Values of make Series from.
|
| 172 |
+
dtype: (Narwhals) dtype. If not provided, the native library
|
| 173 |
+
may auto-infer it from `values`.
|
| 174 |
+
backend: specifies which eager backend instantiate to.
|
| 175 |
+
|
| 176 |
+
`backend` can be specified in various ways
|
| 177 |
+
|
| 178 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 179 |
+
`POLARS`, `MODIN` or `CUDF`.
|
| 180 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
|
| 181 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
|
| 182 |
+
|
| 183 |
+
Examples:
|
| 184 |
+
>>> import pandas as pd
|
| 185 |
+
>>> import narwhals as nw
|
| 186 |
+
>>>
|
| 187 |
+
>>> values = [4, 1, 2, 3]
|
| 188 |
+
>>> nw.new_series(name="a", values=values, dtype=nw.Int32, backend=pd)
|
| 189 |
+
┌─────────────────────┐
|
| 190 |
+
| Narwhals Series |
|
| 191 |
+
|---------------------|
|
| 192 |
+
|0 4 |
|
| 193 |
+
|1 1 |
|
| 194 |
+
|2 2 |
|
| 195 |
+
|3 3 |
|
| 196 |
+
|Name: a, dtype: int32|
|
| 197 |
+
└─────────────────────┘
|
| 198 |
+
"""
|
| 199 |
+
return _new_series_impl(name, values, dtype, backend=backend)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _new_series_impl(
|
| 203 |
+
name: str,
|
| 204 |
+
values: Any,
|
| 205 |
+
dtype: IntoDType | None = None,
|
| 206 |
+
*,
|
| 207 |
+
backend: IntoBackend[EagerAllowed],
|
| 208 |
+
) -> Series[Any]:
|
| 209 |
+
implementation = Implementation.from_backend(backend)
|
| 210 |
+
if is_eager_allowed(implementation):
|
| 211 |
+
ns = Version.MAIN.namespace.from_backend(implementation).compliant
|
| 212 |
+
series = ns._series.from_iterable(values, name=name, context=ns, dtype=dtype)
|
| 213 |
+
return series.to_narwhals()
|
| 214 |
+
if implementation is Implementation.UNKNOWN: # pragma: no cover
|
| 215 |
+
_native_namespace = implementation.to_native_namespace()
|
| 216 |
+
try:
|
| 217 |
+
native_series: NativeSeries = _native_namespace.new_series(
|
| 218 |
+
name, values, dtype
|
| 219 |
+
)
|
| 220 |
+
return from_native(native_series, series_only=True).alias(name)
|
| 221 |
+
except AttributeError as e:
|
| 222 |
+
msg = "Unknown namespace is expected to implement `new_series` constructor."
|
| 223 |
+
raise AttributeError(msg) from e
|
| 224 |
+
msg = (
|
| 225 |
+
f"{implementation} support in Narwhals is lazy-only, but `new_series` is an eager-only function.\n\n"
|
| 226 |
+
"Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n"
|
| 227 |
+
f" nw.new_series('a', [1,2,3], backend='pyarrow').to_frame().lazy('{implementation}')"
|
| 228 |
+
)
|
| 229 |
+
raise ValueError(msg)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@deprecate_native_namespace(warn_version="1.26.0")
|
| 233 |
+
def from_dict(
|
| 234 |
+
data: Mapping[str, Any],
|
| 235 |
+
schema: IntoSchema | Mapping[str, DType | None] | None = None,
|
| 236 |
+
*,
|
| 237 |
+
backend: IntoBackend[EagerAllowed] | None = None,
|
| 238 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 239 |
+
) -> DataFrame[Any]:
|
| 240 |
+
"""Instantiate DataFrame from dictionary.
|
| 241 |
+
|
| 242 |
+
Indexes (if present, for pandas-like backends) are aligned following
|
| 243 |
+
the [left-hand-rule](../concepts/pandas_index.md/).
|
| 244 |
+
|
| 245 |
+
Notes:
|
| 246 |
+
For pandas-like dataframes, conversion to schema is applied after dataframe
|
| 247 |
+
creation.
|
| 248 |
+
|
| 249 |
+
Arguments:
|
| 250 |
+
data: Dictionary to create DataFrame from.
|
| 251 |
+
schema: The DataFrame schema as Schema or dict of {name: type}. If not
|
| 252 |
+
specified, the schema will be inferred by the native library. If
|
| 253 |
+
any `dtype` is `None`, the data type for that column will be inferred
|
| 254 |
+
by the native library.
|
| 255 |
+
backend: specifies which eager backend instantiate to. Only
|
| 256 |
+
necessary if inputs are not Narwhals Series.
|
| 257 |
+
|
| 258 |
+
`backend` can be specified in various ways
|
| 259 |
+
|
| 260 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 261 |
+
`POLARS`, `MODIN` or `CUDF`.
|
| 262 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
|
| 263 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
|
| 264 |
+
native_namespace: deprecated, same as `backend`.
|
| 265 |
+
|
| 266 |
+
Examples:
|
| 267 |
+
>>> import pandas as pd
|
| 268 |
+
>>> import narwhals as nw
|
| 269 |
+
>>> data = {"c": [5, 2], "d": [1, 4]}
|
| 270 |
+
>>> nw.from_dict(data, backend="pandas")
|
| 271 |
+
┌──────────────────┐
|
| 272 |
+
|Narwhals DataFrame|
|
| 273 |
+
|------------------|
|
| 274 |
+
| c d |
|
| 275 |
+
| 0 5 1 |
|
| 276 |
+
| 1 2 4 |
|
| 277 |
+
└──────────────────┘
|
| 278 |
+
"""
|
| 279 |
+
if backend is None:
|
| 280 |
+
data, backend = _from_dict_no_backend(data)
|
| 281 |
+
if schema and data and (diff := set(schema.keys()).symmetric_difference(data.keys())):
|
| 282 |
+
msg = f"Keys in `schema` and `data` are expected to match, found unmatched keys: {diff}"
|
| 283 |
+
raise InvalidOperationError(msg)
|
| 284 |
+
implementation = Implementation.from_backend(backend)
|
| 285 |
+
if is_eager_allowed(implementation):
|
| 286 |
+
ns = Version.MAIN.namespace.from_backend(implementation).compliant
|
| 287 |
+
return ns._dataframe.from_dict(data, schema=schema, context=ns).to_narwhals()
|
| 288 |
+
if implementation is Implementation.UNKNOWN: # pragma: no cover
|
| 289 |
+
_native_namespace = implementation.to_native_namespace()
|
| 290 |
+
try:
|
| 291 |
+
# implementation is UNKNOWN, Narwhals extension using this feature should
|
| 292 |
+
# implement `from_dict` function in the top-level namespace.
|
| 293 |
+
native_frame: NativeDataFrame = _native_namespace.from_dict(
|
| 294 |
+
data, schema=schema
|
| 295 |
+
)
|
| 296 |
+
except AttributeError as e:
|
| 297 |
+
msg = "Unknown namespace is expected to implement `from_dict` function."
|
| 298 |
+
raise AttributeError(msg) from e
|
| 299 |
+
return from_native(native_frame, eager_only=True)
|
| 300 |
+
msg = (
|
| 301 |
+
f"{implementation} support in Narwhals is lazy-only, but `from_dict` is an eager-only function.\n\n"
|
| 302 |
+
"Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n"
|
| 303 |
+
f" nw.from_dict({{'a': [1, 2]}}, backend='pyarrow').lazy('{implementation}')"
|
| 304 |
+
)
|
| 305 |
+
raise ValueError(msg)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def _from_dict_no_backend(
|
| 309 |
+
data: Mapping[str, Series[Any] | Any], /
|
| 310 |
+
) -> tuple[dict[str, Series[Any] | Any], ModuleType]:
|
| 311 |
+
for val in data.values():
|
| 312 |
+
if is_narwhals_series(val):
|
| 313 |
+
native_namespace = val.__native_namespace__()
|
| 314 |
+
break
|
| 315 |
+
else:
|
| 316 |
+
msg = "Calling `from_dict` without `backend` is only supported if all input values are already Narwhals Series"
|
| 317 |
+
raise TypeError(msg)
|
| 318 |
+
data = {key: to_native(value, pass_through=True) for key, value in data.items()}
|
| 319 |
+
return data, native_namespace
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def from_dicts(
|
| 323 |
+
data: Sequence[Mapping[str, Any]],
|
| 324 |
+
schema: IntoSchema | Mapping[str, DType | None] | None = None,
|
| 325 |
+
*,
|
| 326 |
+
backend: IntoBackend[EagerAllowed],
|
| 327 |
+
) -> DataFrame[Any]:
|
| 328 |
+
"""Instantiate DataFrame from a sequence of dictionaries representing rows.
|
| 329 |
+
|
| 330 |
+
Notes:
|
| 331 |
+
For pandas-like dataframes, conversion to schema is applied after dataframe
|
| 332 |
+
creation.
|
| 333 |
+
|
| 334 |
+
Arguments:
|
| 335 |
+
data: Sequence with dictionaries mapping column name to value.
|
| 336 |
+
schema: The DataFrame schema as Schema or dict of {name: type}. If not
|
| 337 |
+
specified, the schema will be inferred by the native library. If
|
| 338 |
+
any `dtype` is `None`, the data type for that column will be inferred
|
| 339 |
+
by the native library.
|
| 340 |
+
backend: Specifies which eager backend instantiate to.
|
| 341 |
+
|
| 342 |
+
`backend` can be specified in various ways
|
| 343 |
+
|
| 344 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 345 |
+
`POLARS`, `MODIN` or `CUDF`.
|
| 346 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
|
| 347 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
|
| 348 |
+
|
| 349 |
+
Tip:
|
| 350 |
+
If you expect non-uniform keys in `data`, consider passing `schema` for
|
| 351 |
+
more consistent results, as **inference varies between backends**:
|
| 352 |
+
|
| 353 |
+
- pandas uses all rows
|
| 354 |
+
- polars uses the first 100 rows
|
| 355 |
+
- pyarrow uses only the first row
|
| 356 |
+
|
| 357 |
+
Examples:
|
| 358 |
+
>>> import polars as pl
|
| 359 |
+
>>> import narwhals as nw
|
| 360 |
+
>>> data = [
|
| 361 |
+
... {"item": "apple", "weight": 80, "price": 0.60},
|
| 362 |
+
... {"item": "egg", "weight": 55, "price": 0.40},
|
| 363 |
+
... ]
|
| 364 |
+
>>> nw.DataFrame.from_dicts(data, backend="polars")
|
| 365 |
+
┌──────────────────────────┐
|
| 366 |
+
| Narwhals DataFrame |
|
| 367 |
+
|--------------------------|
|
| 368 |
+
|shape: (2, 3) |
|
| 369 |
+
|┌───────┬────────┬───────┐|
|
| 370 |
+
|│ item ┆ weight ┆ price │|
|
| 371 |
+
|│ --- ┆ --- ┆ --- │|
|
| 372 |
+
|│ str ┆ i64 ┆ f64 │|
|
| 373 |
+
|╞═══════╪════════╪═══════╡|
|
| 374 |
+
|│ apple ┆ 80 ┆ 0.6 │|
|
| 375 |
+
|│ egg ┆ 55 ┆ 0.4 │|
|
| 376 |
+
|└───────┴────────┴───────┘|
|
| 377 |
+
└──────────────────────────┘
|
| 378 |
+
"""
|
| 379 |
+
return Version.MAIN.dataframe.from_dicts(data, schema, backend=backend)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def from_numpy(
|
| 383 |
+
data: _2DArray,
|
| 384 |
+
schema: IntoSchema | Sequence[str] | None = None,
|
| 385 |
+
*,
|
| 386 |
+
backend: IntoBackend[EagerAllowed],
|
| 387 |
+
) -> DataFrame[Any]:
|
| 388 |
+
"""Construct a DataFrame from a NumPy ndarray.
|
| 389 |
+
|
| 390 |
+
Notes:
|
| 391 |
+
Only row orientation is currently supported.
|
| 392 |
+
|
| 393 |
+
For pandas-like dataframes, conversion to schema is applied after dataframe
|
| 394 |
+
creation.
|
| 395 |
+
|
| 396 |
+
Arguments:
|
| 397 |
+
data: Two-dimensional data represented as a NumPy ndarray.
|
| 398 |
+
schema: The DataFrame schema as Schema, dict of {name: type}, or a sequence of str.
|
| 399 |
+
backend: specifies which eager backend instantiate to.
|
| 400 |
+
|
| 401 |
+
`backend` can be specified in various ways
|
| 402 |
+
|
| 403 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 404 |
+
`POLARS`, `MODIN` or `CUDF`.
|
| 405 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
|
| 406 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
|
| 407 |
+
|
| 408 |
+
Examples:
|
| 409 |
+
>>> import numpy as np
|
| 410 |
+
>>> import pyarrow as pa
|
| 411 |
+
>>> import narwhals as nw
|
| 412 |
+
>>>
|
| 413 |
+
>>> arr = np.array([[5, 2, 1], [1, 4, 3]])
|
| 414 |
+
>>> schema = {"c": nw.Int16(), "d": nw.Float32(), "e": nw.Int8()}
|
| 415 |
+
>>> nw.from_numpy(arr, schema=schema, backend="pyarrow")
|
| 416 |
+
┌──────────────────┐
|
| 417 |
+
|Narwhals DataFrame|
|
| 418 |
+
|------------------|
|
| 419 |
+
| pyarrow.Table |
|
| 420 |
+
| c: int16 |
|
| 421 |
+
| d: float |
|
| 422 |
+
| e: int8 |
|
| 423 |
+
| ---- |
|
| 424 |
+
| c: [[5,1]] |
|
| 425 |
+
| d: [[2,4]] |
|
| 426 |
+
| e: [[1,3]] |
|
| 427 |
+
└──────────────────┘
|
| 428 |
+
"""
|
| 429 |
+
if not is_numpy_array_2d(data):
|
| 430 |
+
msg = "`from_numpy` only accepts 2D numpy arrays"
|
| 431 |
+
raise ValueError(msg)
|
| 432 |
+
if not _is_into_schema(schema):
|
| 433 |
+
msg = (
|
| 434 |
+
"`schema` is expected to be one of the following types: "
|
| 435 |
+
"IntoSchema | Sequence[str]. "
|
| 436 |
+
f"Got {type(schema)}."
|
| 437 |
+
)
|
| 438 |
+
raise TypeError(msg)
|
| 439 |
+
implementation = Implementation.from_backend(backend)
|
| 440 |
+
if is_eager_allowed(implementation):
|
| 441 |
+
ns = Version.MAIN.namespace.from_backend(implementation).compliant
|
| 442 |
+
return ns.from_numpy(data, schema).to_narwhals()
|
| 443 |
+
if implementation is Implementation.UNKNOWN: # pragma: no cover
|
| 444 |
+
_native_namespace = implementation.to_native_namespace()
|
| 445 |
+
try:
|
| 446 |
+
# implementation is UNKNOWN, Narwhals extension using this feature should
|
| 447 |
+
# implement `from_numpy` function in the top-level namespace.
|
| 448 |
+
native_frame: NativeDataFrame = _native_namespace.from_numpy(
|
| 449 |
+
data, schema=schema
|
| 450 |
+
)
|
| 451 |
+
except AttributeError as e:
|
| 452 |
+
msg = "Unknown namespace is expected to implement `from_numpy` function."
|
| 453 |
+
raise AttributeError(msg) from e
|
| 454 |
+
return from_native(native_frame, eager_only=True)
|
| 455 |
+
msg = (
|
| 456 |
+
f"{implementation} support in Narwhals is lazy-only, but `from_numpy` is an eager-only function.\n\n"
|
| 457 |
+
"Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n"
|
| 458 |
+
f" nw.from_numpy(arr, backend='pyarrow').lazy('{implementation}')"
|
| 459 |
+
)
|
| 460 |
+
raise ValueError(msg)
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def _is_into_schema(obj: Any) -> TypeIs[_IntoSchema]:
|
| 464 |
+
from narwhals.schema import Schema
|
| 465 |
+
|
| 466 |
+
return (
|
| 467 |
+
obj is None or isinstance(obj, (Mapping, Schema)) or is_sequence_but_not_str(obj)
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def from_arrow(
|
| 472 |
+
native_frame: IntoArrowTable, *, backend: IntoBackend[EagerAllowed]
|
| 473 |
+
) -> DataFrame[Any]: # pragma: no cover
|
| 474 |
+
"""Construct a DataFrame from an object which supports the PyCapsule Interface.
|
| 475 |
+
|
| 476 |
+
Arguments:
|
| 477 |
+
native_frame: Object which implements `__arrow_c_stream__`.
|
| 478 |
+
backend: specifies which eager backend instantiate to.
|
| 479 |
+
|
| 480 |
+
`backend` can be specified in various ways
|
| 481 |
+
|
| 482 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 483 |
+
`POLARS`, `MODIN` or `CUDF`.
|
| 484 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
|
| 485 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
|
| 486 |
+
|
| 487 |
+
Examples:
|
| 488 |
+
>>> import pandas as pd
|
| 489 |
+
>>> import polars as pl
|
| 490 |
+
>>> import narwhals as nw
|
| 491 |
+
>>>
|
| 492 |
+
>>> df_native = pd.DataFrame({"a": [1, 2], "b": [4.2, 5.1]})
|
| 493 |
+
>>> nw.from_arrow(df_native, backend="polars")
|
| 494 |
+
┌──────────────────┐
|
| 495 |
+
|Narwhals DataFrame|
|
| 496 |
+
|------------------|
|
| 497 |
+
| shape: (2, 2) |
|
| 498 |
+
| ┌─────┬─────┐ |
|
| 499 |
+
| │ a ┆ b │ |
|
| 500 |
+
| │ --- ┆ --- │ |
|
| 501 |
+
| │ i64 ┆ f64 │ |
|
| 502 |
+
| ╞═════╪═════╡ |
|
| 503 |
+
| │ 1 ┆ 4.2 │ |
|
| 504 |
+
| │ 2 ┆ 5.1 │ |
|
| 505 |
+
| └─────┴─────┘ |
|
| 506 |
+
└──────────────────┘
|
| 507 |
+
"""
|
| 508 |
+
if not (supports_arrow_c_stream(native_frame) or is_pyarrow_table(native_frame)):
|
| 509 |
+
msg = f"Given object of type {type(native_frame)} does not support PyCapsule interface"
|
| 510 |
+
raise TypeError(msg)
|
| 511 |
+
implementation = Implementation.from_backend(backend)
|
| 512 |
+
if is_eager_allowed(implementation):
|
| 513 |
+
ns = Version.MAIN.namespace.from_backend(implementation).compliant
|
| 514 |
+
return ns._dataframe.from_arrow(native_frame, context=ns).to_narwhals()
|
| 515 |
+
if implementation is Implementation.UNKNOWN: # pragma: no cover
|
| 516 |
+
_native_namespace = implementation.to_native_namespace()
|
| 517 |
+
try:
|
| 518 |
+
# implementation is UNKNOWN, Narwhals extension using this feature should
|
| 519 |
+
# implement PyCapsule support
|
| 520 |
+
native: NativeDataFrame = _native_namespace.DataFrame(native_frame)
|
| 521 |
+
except AttributeError as e:
|
| 522 |
+
msg = "Unknown namespace is expected to implement `DataFrame` class which accepts object which supports PyCapsule Interface."
|
| 523 |
+
raise AttributeError(msg) from e
|
| 524 |
+
return from_native(native, eager_only=True)
|
| 525 |
+
msg = (
|
| 526 |
+
f"{implementation} support in Narwhals is lazy-only, but `from_arrow` is an eager-only function.\n\n"
|
| 527 |
+
"Hint: you may want to use an eager backend and then call `.lazy`, e.g.:\n\n"
|
| 528 |
+
f" nw.from_arrow(df, backend='pyarrow').lazy('{implementation}')"
|
| 529 |
+
)
|
| 530 |
+
raise ValueError(msg)
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def _get_sys_info() -> dict[str, str]:
|
| 534 |
+
"""System information.
|
| 535 |
+
|
| 536 |
+
Returns system and Python version information
|
| 537 |
+
|
| 538 |
+
Copied from sklearn
|
| 539 |
+
|
| 540 |
+
Returns:
|
| 541 |
+
Dictionary with system info.
|
| 542 |
+
"""
|
| 543 |
+
python = sys.version.replace("\n", " ")
|
| 544 |
+
|
| 545 |
+
blob = (
|
| 546 |
+
("python", python),
|
| 547 |
+
("executable", sys.executable),
|
| 548 |
+
("machine", platform.platform()),
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
return dict(blob)
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def _get_deps_info() -> dict[str, str]:
|
| 555 |
+
"""Overview of the installed version of main dependencies.
|
| 556 |
+
|
| 557 |
+
This function does not import the modules to collect the version numbers
|
| 558 |
+
but instead relies on standard Python package metadata.
|
| 559 |
+
|
| 560 |
+
Returns version information on relevant Python libraries
|
| 561 |
+
|
| 562 |
+
This function and show_versions were copied from sklearn and adapted
|
| 563 |
+
|
| 564 |
+
Returns:
|
| 565 |
+
Mapping from dependency to version.
|
| 566 |
+
"""
|
| 567 |
+
from importlib.metadata import distributions
|
| 568 |
+
|
| 569 |
+
extra_names = ("narwhals", "numpy")
|
| 570 |
+
member_names = Implementation._member_names_
|
| 571 |
+
exclude = {"PYSPARK_CONNECT", "UNKNOWN"}
|
| 572 |
+
target_names = tuple(
|
| 573 |
+
name.lower() for name in (*extra_names, *member_names) if name not in exclude
|
| 574 |
+
)
|
| 575 |
+
result = dict.fromkeys(target_names, "") # Initialize with empty strings
|
| 576 |
+
|
| 577 |
+
for dist in distributions():
|
| 578 |
+
dist_name, dist_version = dist.name.lower(), dist.version
|
| 579 |
+
|
| 580 |
+
if dist_name in result: # exact match
|
| 581 |
+
result[dist_name] = dist_version
|
| 582 |
+
else: # prefix match
|
| 583 |
+
for target in target_names:
|
| 584 |
+
if not result[target] and dist_name.startswith(
|
| 585 |
+
target
|
| 586 |
+
): # pragma: no cover
|
| 587 |
+
result[target] = dist_version
|
| 588 |
+
break
|
| 589 |
+
|
| 590 |
+
return result
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def show_versions() -> None:
|
| 594 |
+
"""Print useful debugging information.
|
| 595 |
+
|
| 596 |
+
Examples:
|
| 597 |
+
>>> from narwhals import show_versions
|
| 598 |
+
>>> show_versions() # doctest: +SKIP
|
| 599 |
+
"""
|
| 600 |
+
sys_info = _get_sys_info()
|
| 601 |
+
deps_info = _get_deps_info()
|
| 602 |
+
|
| 603 |
+
print("\nSystem:") # noqa: T201
|
| 604 |
+
for k, stat in sys_info.items():
|
| 605 |
+
print(f"{k:>10}: {stat}") # noqa: T201
|
| 606 |
+
|
| 607 |
+
print("\nPython dependencies:") # noqa: T201
|
| 608 |
+
for k, stat in deps_info.items():
|
| 609 |
+
print(f"{k:>13}: {stat}") # noqa: T201
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def _validate_separators(
|
| 613 |
+
separator: str, native_separators: tuple[str, ...], **kwargs: Any
|
| 614 |
+
) -> None:
|
| 615 |
+
for native_separator in native_separators:
|
| 616 |
+
if native_separator in kwargs and kwargs[native_separator] != separator:
|
| 617 |
+
msg = (
|
| 618 |
+
f"`separator` and `{native_separator}` do not match: "
|
| 619 |
+
f"`separator`={separator} and `{native_separator}`={kwargs[native_separator]}."
|
| 620 |
+
)
|
| 621 |
+
raise TypeError(msg)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def _validate_separator_pyarrow(separator: str, **kwargs: Any) -> Any:
|
| 625 |
+
if "parse_options" in kwargs:
|
| 626 |
+
parse_options = kwargs.pop("parse_options")
|
| 627 |
+
if parse_options.delimiter != separator:
|
| 628 |
+
msg = (
|
| 629 |
+
"`separator` and `parse_options.delimiter` do not match: "
|
| 630 |
+
f"`separator`={separator} and `delimiter`={parse_options.delimiter}."
|
| 631 |
+
)
|
| 632 |
+
raise TypeError(msg)
|
| 633 |
+
return kwargs
|
| 634 |
+
from pyarrow import csv # ignore-banned-import
|
| 635 |
+
|
| 636 |
+
return {"parse_options": csv.ParseOptions(delimiter=separator)}
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def read_csv(
|
| 640 |
+
source: FileSource,
|
| 641 |
+
*,
|
| 642 |
+
backend: IntoBackend[EagerAllowed],
|
| 643 |
+
separator: str = ",",
|
| 644 |
+
**kwargs: Any,
|
| 645 |
+
) -> DataFrame[Any]:
|
| 646 |
+
"""Read a CSV file into a DataFrame.
|
| 647 |
+
|
| 648 |
+
Arguments:
|
| 649 |
+
source: Path to a file.
|
| 650 |
+
backend: The eager backend for DataFrame creation.
|
| 651 |
+
`backend` can be specified in various ways
|
| 652 |
+
|
| 653 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 654 |
+
`POLARS`, `MODIN` or `CUDF`.
|
| 655 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
|
| 656 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
|
| 657 |
+
separator: Single byte character to use as separator in the file.
|
| 658 |
+
kwargs: Extra keyword arguments which are passed to the native CSV reader.
|
| 659 |
+
For example, you could use
|
| 660 |
+
`nw.read_csv('file.csv', backend='pandas', engine='pyarrow')`.
|
| 661 |
+
|
| 662 |
+
Examples:
|
| 663 |
+
>>> import narwhals as nw
|
| 664 |
+
>>> nw.read_csv("file.csv", backend="pandas") # doctest:+SKIP
|
| 665 |
+
┌──────────────────┐
|
| 666 |
+
|Narwhals DataFrame|
|
| 667 |
+
|------------------|
|
| 668 |
+
| a b |
|
| 669 |
+
| 0 1 4 |
|
| 670 |
+
| 1 2 5 |
|
| 671 |
+
└──────────────────┘
|
| 672 |
+
"""
|
| 673 |
+
impl = Implementation.from_backend(backend)
|
| 674 |
+
native_namespace = impl.to_native_namespace()
|
| 675 |
+
native_frame: NativeDataFrame
|
| 676 |
+
if impl in {Implementation.PANDAS, Implementation.MODIN, Implementation.CUDF}:
|
| 677 |
+
_validate_separators(separator, ("sep",), **kwargs)
|
| 678 |
+
native_frame = native_namespace.read_csv(
|
| 679 |
+
normalize_path(source), sep=separator, **kwargs
|
| 680 |
+
)
|
| 681 |
+
elif impl is Implementation.POLARS:
|
| 682 |
+
native_frame = native_namespace.read_csv(
|
| 683 |
+
normalize_path(source), separator=separator, **kwargs
|
| 684 |
+
)
|
| 685 |
+
elif impl is Implementation.PYARROW:
|
| 686 |
+
kwargs = _validate_separator_pyarrow(separator, **kwargs)
|
| 687 |
+
from pyarrow import csv # ignore-banned-import
|
| 688 |
+
|
| 689 |
+
native_frame = csv.read_csv(source, **kwargs)
|
| 690 |
+
elif impl in {
|
| 691 |
+
Implementation.PYSPARK,
|
| 692 |
+
Implementation.DASK,
|
| 693 |
+
Implementation.DUCKDB,
|
| 694 |
+
Implementation.IBIS,
|
| 695 |
+
Implementation.SQLFRAME,
|
| 696 |
+
Implementation.PYSPARK_CONNECT,
|
| 697 |
+
}:
|
| 698 |
+
msg = (
|
| 699 |
+
f"Expected eager backend, found {impl}.\n\n"
|
| 700 |
+
f"Hint: use nw.scan_csv(source={source}, backend={backend})"
|
| 701 |
+
)
|
| 702 |
+
raise ValueError(msg)
|
| 703 |
+
else: # pragma: no cover
|
| 704 |
+
try:
|
| 705 |
+
# implementation is UNKNOWN, Narwhals extension using this feature should
|
| 706 |
+
# implement `read_csv` function in the top-level namespace.
|
| 707 |
+
native_frame = native_namespace.read_csv(source=source, **kwargs)
|
| 708 |
+
except AttributeError as e:
|
| 709 |
+
msg = "Unknown namespace is expected to implement `read_csv` function."
|
| 710 |
+
raise AttributeError(msg) from e
|
| 711 |
+
return from_native(native_frame, eager_only=True)
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
def scan_csv(
|
| 715 |
+
source: FileSource,
|
| 716 |
+
*,
|
| 717 |
+
backend: IntoBackend[Backend],
|
| 718 |
+
separator: str = ",",
|
| 719 |
+
**kwargs: Any,
|
| 720 |
+
) -> LazyFrame[Any]:
|
| 721 |
+
"""Lazily read from a CSV file.
|
| 722 |
+
|
| 723 |
+
For the libraries that do not support lazy dataframes, the function reads
|
| 724 |
+
a csv file eagerly and then converts the resulting dataframe to a lazyframe.
|
| 725 |
+
|
| 726 |
+
Arguments:
|
| 727 |
+
source: Path to a file.
|
| 728 |
+
backend: The eager backend for DataFrame creation.
|
| 729 |
+
`backend` can be specified in various ways
|
| 730 |
+
|
| 731 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 732 |
+
`POLARS`, `MODIN` or `CUDF`.
|
| 733 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
|
| 734 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
|
| 735 |
+
separator: Single byte character to use as separator in the file.
|
| 736 |
+
kwargs: Extra keyword arguments which are passed to the native CSV reader.
|
| 737 |
+
For example, you could use
|
| 738 |
+
`nw.scan_csv('file.csv', backend=pd, engine='pyarrow')`.
|
| 739 |
+
|
| 740 |
+
Examples:
|
| 741 |
+
>>> import duckdb
|
| 742 |
+
>>> import narwhals as nw
|
| 743 |
+
>>>
|
| 744 |
+
>>> nw.scan_csv("file.csv", backend="duckdb").to_native() # doctest:+SKIP
|
| 745 |
+
┌─────────┬───────┐
|
| 746 |
+
│ a │ b │
|
| 747 |
+
│ varchar │ int32 │
|
| 748 |
+
├─────────┼───────┤
|
| 749 |
+
│ x │ 1 │
|
| 750 |
+
│ y │ 2 │
|
| 751 |
+
│ z │ 3 │
|
| 752 |
+
└─────────┴───────┘
|
| 753 |
+
"""
|
| 754 |
+
implementation = Implementation.from_backend(backend)
|
| 755 |
+
native_namespace = implementation.to_native_namespace()
|
| 756 |
+
native_frame: NativeDataFrame | NativeLazyFrame
|
| 757 |
+
source = normalize_path(source)
|
| 758 |
+
if implementation is Implementation.POLARS:
|
| 759 |
+
native_frame = native_namespace.scan_csv(source, separator=separator, **kwargs)
|
| 760 |
+
elif implementation in {
|
| 761 |
+
Implementation.PANDAS,
|
| 762 |
+
Implementation.MODIN,
|
| 763 |
+
Implementation.CUDF,
|
| 764 |
+
Implementation.DASK,
|
| 765 |
+
Implementation.IBIS,
|
| 766 |
+
}:
|
| 767 |
+
_validate_separators(separator, ("sep",), **kwargs)
|
| 768 |
+
native_frame = native_namespace.read_csv(source, sep=separator, **kwargs)
|
| 769 |
+
elif implementation is Implementation.DUCKDB:
|
| 770 |
+
_validate_separators(separator, ("delimiter", "delim", "sep"), **kwargs)
|
| 771 |
+
native_frame = native_namespace.read_csv(source, delimiter=separator, **kwargs)
|
| 772 |
+
elif implementation is Implementation.PYARROW:
|
| 773 |
+
kwargs = _validate_separator_pyarrow(separator, **kwargs)
|
| 774 |
+
from pyarrow import csv # ignore-banned-import
|
| 775 |
+
|
| 776 |
+
native_frame = csv.read_csv(source, **kwargs)
|
| 777 |
+
elif implementation.is_spark_like():
|
| 778 |
+
_validate_separators(separator, ("sep", "delimiter"), **kwargs)
|
| 779 |
+
if (session := kwargs.pop("session", None)) is None:
|
| 780 |
+
msg = "Spark like backends require a session object to be passed in `kwargs`."
|
| 781 |
+
raise ValueError(msg)
|
| 782 |
+
csv_reader = session.read.format("csv")
|
| 783 |
+
native_frame = (
|
| 784 |
+
csv_reader.load(source, sep=separator)
|
| 785 |
+
if (
|
| 786 |
+
implementation is Implementation.SQLFRAME
|
| 787 |
+
and implementation._backend_version() < (3, 27, 0)
|
| 788 |
+
)
|
| 789 |
+
else csv_reader.options(sep=separator, **kwargs).load(source)
|
| 790 |
+
)
|
| 791 |
+
else: # pragma: no cover
|
| 792 |
+
try:
|
| 793 |
+
# implementation is UNKNOWN, Narwhals extension using this feature should
|
| 794 |
+
# implement `scan_csv` function in the top-level namespace.
|
| 795 |
+
native_frame = native_namespace.scan_csv(source=source, **kwargs)
|
| 796 |
+
except AttributeError as e:
|
| 797 |
+
msg = "Unknown namespace is expected to implement `scan_csv` function."
|
| 798 |
+
raise AttributeError(msg) from e
|
| 799 |
+
return from_native(native_frame).lazy()
|
| 800 |
+
|
| 801 |
+
|
| 802 |
+
def read_parquet(
|
| 803 |
+
source: FileSource, *, backend: IntoBackend[EagerAllowed], **kwargs: Any
|
| 804 |
+
) -> DataFrame[Any]:
|
| 805 |
+
"""Read into a DataFrame from a parquet file.
|
| 806 |
+
|
| 807 |
+
Arguments:
|
| 808 |
+
source: Path to a file.
|
| 809 |
+
backend: The eager backend for DataFrame creation.
|
| 810 |
+
`backend` can be specified in various ways
|
| 811 |
+
|
| 812 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 813 |
+
`POLARS`, `MODIN` or `CUDF`.
|
| 814 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"` or `"cudf"`.
|
| 815 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin` or `cudf`.
|
| 816 |
+
kwargs: Extra keyword arguments which are passed to the native parquet reader.
|
| 817 |
+
For example, you could use
|
| 818 |
+
`nw.read_parquet('file.parquet', backend=pd, engine='pyarrow')`.
|
| 819 |
+
|
| 820 |
+
Examples:
|
| 821 |
+
>>> import pyarrow as pa
|
| 822 |
+
>>> import narwhals as nw
|
| 823 |
+
>>>
|
| 824 |
+
>>> nw.read_parquet("file.parquet", backend="pyarrow") # doctest:+SKIP
|
| 825 |
+
┌──────────────────┐
|
| 826 |
+
|Narwhals DataFrame|
|
| 827 |
+
|------------------|
|
| 828 |
+
|pyarrow.Table |
|
| 829 |
+
|a: int64 |
|
| 830 |
+
|c: double |
|
| 831 |
+
|---- |
|
| 832 |
+
|a: [[1,2]] |
|
| 833 |
+
|c: [[0.2,0.1]] |
|
| 834 |
+
└──────────────────┘
|
| 835 |
+
"""
|
| 836 |
+
impl = Implementation.from_backend(backend)
|
| 837 |
+
native_namespace = impl.to_native_namespace()
|
| 838 |
+
native_frame: NativeDataFrame
|
| 839 |
+
if impl in {
|
| 840 |
+
Implementation.POLARS,
|
| 841 |
+
Implementation.PANDAS,
|
| 842 |
+
Implementation.MODIN,
|
| 843 |
+
Implementation.CUDF,
|
| 844 |
+
}:
|
| 845 |
+
source = normalize_path(source)
|
| 846 |
+
native_frame = native_namespace.read_parquet(source, **kwargs)
|
| 847 |
+
elif impl is Implementation.PYARROW:
|
| 848 |
+
import pyarrow.parquet as pq # ignore-banned-import
|
| 849 |
+
|
| 850 |
+
native_frame = pq.read_table(source, **kwargs) # type: ignore[arg-type]
|
| 851 |
+
elif impl in {
|
| 852 |
+
Implementation.PYSPARK,
|
| 853 |
+
Implementation.DASK,
|
| 854 |
+
Implementation.DUCKDB,
|
| 855 |
+
Implementation.IBIS,
|
| 856 |
+
Implementation.SQLFRAME,
|
| 857 |
+
Implementation.PYSPARK_CONNECT,
|
| 858 |
+
}:
|
| 859 |
+
msg = (
|
| 860 |
+
f"Expected eager backend, found {impl}.\n\n"
|
| 861 |
+
f"Hint: use nw.scan_parquet(source={source}, backend={backend})"
|
| 862 |
+
)
|
| 863 |
+
raise ValueError(msg)
|
| 864 |
+
else: # pragma: no cover
|
| 865 |
+
try:
|
| 866 |
+
# implementation is UNKNOWN, Narwhals extension using this feature should
|
| 867 |
+
# implement `read_parquet` function in the top-level namespace.
|
| 868 |
+
native_frame = native_namespace.read_parquet(source=source, **kwargs)
|
| 869 |
+
except AttributeError as e:
|
| 870 |
+
msg = "Unknown namespace is expected to implement `read_parquet` function."
|
| 871 |
+
raise AttributeError(msg) from e
|
| 872 |
+
return from_native(native_frame, eager_only=True)
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def scan_parquet(
|
| 876 |
+
source: FileSource, *, backend: IntoBackend[Backend], **kwargs: Any
|
| 877 |
+
) -> LazyFrame[Any]:
|
| 878 |
+
"""Lazily read from a parquet file.
|
| 879 |
+
|
| 880 |
+
For the libraries that do not support lazy dataframes, the function reads
|
| 881 |
+
a parquet file eagerly and then converts the resulting dataframe to a lazyframe.
|
| 882 |
+
|
| 883 |
+
Note:
|
| 884 |
+
Spark like backends require a session object to be passed in `kwargs`.
|
| 885 |
+
|
| 886 |
+
For instance:
|
| 887 |
+
|
| 888 |
+
```py
|
| 889 |
+
import narwhals as nw
|
| 890 |
+
from sqlframe.duckdb import DuckDBSession
|
| 891 |
+
|
| 892 |
+
nw.scan_parquet(source, backend="sqlframe", session=DuckDBSession())
|
| 893 |
+
```
|
| 894 |
+
|
| 895 |
+
Arguments:
|
| 896 |
+
source: Path to a file.
|
| 897 |
+
backend: The eager backend for DataFrame creation.
|
| 898 |
+
`backend` can be specified in various ways
|
| 899 |
+
|
| 900 |
+
- As `Implementation.<BACKEND>` with `BACKEND` being `PANDAS`, `PYARROW`,
|
| 901 |
+
`POLARS`, `MODIN`, `CUDF`, `PYSPARK` or `SQLFRAME`.
|
| 902 |
+
- As a string: `"pandas"`, `"pyarrow"`, `"polars"`, `"modin"`, `"cudf"`,
|
| 903 |
+
`"pyspark"` or `"sqlframe"`.
|
| 904 |
+
- Directly as a module `pandas`, `pyarrow`, `polars`, `modin`, `cudf`,
|
| 905 |
+
`pyspark.sql` or `sqlframe`.
|
| 906 |
+
kwargs: Extra keyword arguments which are passed to the native parquet reader.
|
| 907 |
+
For example, you could use
|
| 908 |
+
`nw.scan_parquet('file.parquet', backend=pd, engine='pyarrow')`.
|
| 909 |
+
|
| 910 |
+
Examples:
|
| 911 |
+
>>> import dask.dataframe as dd
|
| 912 |
+
>>> from sqlframe.duckdb import DuckDBSession
|
| 913 |
+
>>> import narwhals as nw
|
| 914 |
+
>>>
|
| 915 |
+
>>> nw.scan_parquet("file.parquet", backend="dask").collect() # doctest:+SKIP
|
| 916 |
+
┌──────────────────┐
|
| 917 |
+
|Narwhals DataFrame|
|
| 918 |
+
|------------------|
|
| 919 |
+
| a b |
|
| 920 |
+
| 0 1 4 |
|
| 921 |
+
| 1 2 5 |
|
| 922 |
+
└──────────────────┘
|
| 923 |
+
>>> nw.scan_parquet(
|
| 924 |
+
... "file.parquet", backend="sqlframe", session=DuckDBSession()
|
| 925 |
+
... ).collect() # doctest:+SKIP
|
| 926 |
+
┌──────────────────┐
|
| 927 |
+
|Narwhals DataFrame|
|
| 928 |
+
|------------------|
|
| 929 |
+
| pyarrow.Table |
|
| 930 |
+
| a: int64 |
|
| 931 |
+
| b: int64 |
|
| 932 |
+
| ---- |
|
| 933 |
+
| a: [[1,2]] |
|
| 934 |
+
| b: [[4,5]] |
|
| 935 |
+
└──────────────────┘
|
| 936 |
+
"""
|
| 937 |
+
implementation = Implementation.from_backend(backend)
|
| 938 |
+
native_namespace = implementation.to_native_namespace()
|
| 939 |
+
native_frame: NativeDataFrame | NativeLazyFrame
|
| 940 |
+
source = normalize_path(source)
|
| 941 |
+
if implementation is Implementation.POLARS:
|
| 942 |
+
native_frame = native_namespace.scan_parquet(source, **kwargs)
|
| 943 |
+
elif implementation in {
|
| 944 |
+
Implementation.PANDAS,
|
| 945 |
+
Implementation.MODIN,
|
| 946 |
+
Implementation.CUDF,
|
| 947 |
+
Implementation.DASK,
|
| 948 |
+
Implementation.DUCKDB,
|
| 949 |
+
Implementation.IBIS,
|
| 950 |
+
}:
|
| 951 |
+
native_frame = native_namespace.read_parquet(source, **kwargs)
|
| 952 |
+
elif implementation is Implementation.PYARROW:
|
| 953 |
+
import pyarrow.parquet as pq # ignore-banned-import
|
| 954 |
+
|
| 955 |
+
native_frame = pq.read_table(source, **kwargs)
|
| 956 |
+
elif implementation.is_spark_like():
|
| 957 |
+
if (session := kwargs.pop("session", None)) is None:
|
| 958 |
+
msg = "Spark like backends require a session object to be passed in `kwargs`."
|
| 959 |
+
raise ValueError(msg)
|
| 960 |
+
pq_reader = session.read.format("parquet")
|
| 961 |
+
native_frame = (
|
| 962 |
+
pq_reader.load(source)
|
| 963 |
+
if (
|
| 964 |
+
implementation is Implementation.SQLFRAME
|
| 965 |
+
and implementation._backend_version() < (3, 27, 0)
|
| 966 |
+
)
|
| 967 |
+
else pq_reader.options(**kwargs).load(source)
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
else: # pragma: no cover
|
| 971 |
+
try:
|
| 972 |
+
# implementation is UNKNOWN, Narwhals extension using this feature should
|
| 973 |
+
# implement `scan_parquet` function in the top-level namespace.
|
| 974 |
+
native_frame = native_namespace.scan_parquet(source=source, **kwargs)
|
| 975 |
+
except AttributeError as e:
|
| 976 |
+
msg = "Unknown namespace is expected to implement `scan_parquet` function."
|
| 977 |
+
raise AttributeError(msg) from e
|
| 978 |
+
return from_native(native_frame).lazy()
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def col(*names: str | Iterable[str]) -> Expr:
|
| 982 |
+
"""Creates an expression that references one or more columns by their name(s).
|
| 983 |
+
|
| 984 |
+
Arguments:
|
| 985 |
+
names: Name(s) of the columns to use.
|
| 986 |
+
|
| 987 |
+
Examples:
|
| 988 |
+
>>> import polars as pl
|
| 989 |
+
>>> import narwhals as nw
|
| 990 |
+
>>>
|
| 991 |
+
>>> df_native = pl.DataFrame({"a": [1, 2], "b": [3, 4], "c": ["x", "z"]})
|
| 992 |
+
>>> nw.from_native(df_native).select(nw.col("a", "b") * nw.col("b"))
|
| 993 |
+
┌──────────────────┐
|
| 994 |
+
|Narwhals DataFrame|
|
| 995 |
+
|------------------|
|
| 996 |
+
| shape: (2, 2) |
|
| 997 |
+
| ┌─────┬─────┐ |
|
| 998 |
+
| │ a ┆ b │ |
|
| 999 |
+
| │ --- ┆ --- │ |
|
| 1000 |
+
| │ i64 ┆ i64 │ |
|
| 1001 |
+
| ╞═════╪═════╡ |
|
| 1002 |
+
| │ 3 ┆ 9 │ |
|
| 1003 |
+
| │ 8 ┆ 16 │ |
|
| 1004 |
+
| └─────┴─────┘ |
|
| 1005 |
+
└──────────────────┘
|
| 1006 |
+
"""
|
| 1007 |
+
flat_names = flatten(names)
|
| 1008 |
+
return Expr(ExprNode(ExprKind.COL, "col", names=flat_names))
|
| 1009 |
+
|
| 1010 |
+
|
| 1011 |
+
def exclude(*names: str | Iterable[str]) -> Expr:
|
| 1012 |
+
"""Creates an expression that excludes columns by their name(s).
|
| 1013 |
+
|
| 1014 |
+
Arguments:
|
| 1015 |
+
names: Name(s) of the columns to exclude.
|
| 1016 |
+
|
| 1017 |
+
Examples:
|
| 1018 |
+
>>> import polars as pl
|
| 1019 |
+
>>> import narwhals as nw
|
| 1020 |
+
>>>
|
| 1021 |
+
>>> df_native = pl.DataFrame({"a": [1, 2], "b": [3, 4], "c": ["x", "z"]})
|
| 1022 |
+
>>> nw.from_native(df_native).select(nw.exclude("c", "a"))
|
| 1023 |
+
┌──────────────────┐
|
| 1024 |
+
|Narwhals DataFrame|
|
| 1025 |
+
|------------------|
|
| 1026 |
+
| shape: (2, 1) |
|
| 1027 |
+
| ┌─────┐ |
|
| 1028 |
+
| │ b │ |
|
| 1029 |
+
| │ --- │ |
|
| 1030 |
+
| │ i64 │ |
|
| 1031 |
+
| ╞═════╡ |
|
| 1032 |
+
| │ 3 │ |
|
| 1033 |
+
| │ 4 │ |
|
| 1034 |
+
| └─────┘ |
|
| 1035 |
+
└──────────────────┘
|
| 1036 |
+
"""
|
| 1037 |
+
return Expr(ExprNode(ExprKind.EXCLUDE, "exclude", names=frozenset(flatten(names))))
|
| 1038 |
+
|
| 1039 |
+
|
| 1040 |
+
def nth(*indices: int | Sequence[int]) -> Expr:
|
| 1041 |
+
"""Creates an expression that references one or more columns by their index(es).
|
| 1042 |
+
|
| 1043 |
+
Notes:
|
| 1044 |
+
`nth` is not supported for Polars version<1.0.0. Please use
|
| 1045 |
+
[`narwhals.col`][] instead.
|
| 1046 |
+
|
| 1047 |
+
Arguments:
|
| 1048 |
+
indices: One or more indices representing the columns to retrieve.
|
| 1049 |
+
|
| 1050 |
+
Examples:
|
| 1051 |
+
>>> import pyarrow as pa
|
| 1052 |
+
>>> import narwhals as nw
|
| 1053 |
+
>>>
|
| 1054 |
+
>>> df_native = pa.table({"a": [1, 2], "b": [3, 4], "c": [0.123, 3.14]})
|
| 1055 |
+
>>> nw.from_native(df_native).select(nw.nth(0, 2) * 2)
|
| 1056 |
+
┌──────────────────┐
|
| 1057 |
+
|Narwhals DataFrame|
|
| 1058 |
+
|------------------|
|
| 1059 |
+
|pyarrow.Table |
|
| 1060 |
+
|a: int64 |
|
| 1061 |
+
|c: double |
|
| 1062 |
+
|---- |
|
| 1063 |
+
|a: [[2,4]] |
|
| 1064 |
+
|c: [[0.246,6.28]] |
|
| 1065 |
+
└──────────────────┘
|
| 1066 |
+
"""
|
| 1067 |
+
flat_indices = flatten(indices)
|
| 1068 |
+
return Expr(ExprNode(ExprKind.NTH, "nth", indices=flat_indices))
|
| 1069 |
+
|
| 1070 |
+
|
| 1071 |
+
# Add underscore so it doesn't conflict with builtin `all`
|
| 1072 |
+
def all_() -> Expr:
|
| 1073 |
+
"""Instantiate an expression representing all columns.
|
| 1074 |
+
|
| 1075 |
+
Examples:
|
| 1076 |
+
>>> import pandas as pd
|
| 1077 |
+
>>> import narwhals as nw
|
| 1078 |
+
>>>
|
| 1079 |
+
>>> df_native = pd.DataFrame({"a": [1, 2], "b": [3.14, 0.123]})
|
| 1080 |
+
>>> nw.from_native(df_native).select(nw.all() * 2)
|
| 1081 |
+
┌──────────────────┐
|
| 1082 |
+
|Narwhals DataFrame|
|
| 1083 |
+
|------------------|
|
| 1084 |
+
| a b |
|
| 1085 |
+
| 0 2 6.280 |
|
| 1086 |
+
| 1 4 0.246 |
|
| 1087 |
+
└──────────────────┘
|
| 1088 |
+
"""
|
| 1089 |
+
return Expr(ExprNode(ExprKind.ALL, "all"))
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
# Add underscore so it doesn't conflict with builtin `len`
|
| 1093 |
+
def len_() -> Expr:
|
| 1094 |
+
"""Return the number of rows.
|
| 1095 |
+
|
| 1096 |
+
Examples:
|
| 1097 |
+
>>> import polars as pl
|
| 1098 |
+
>>> import narwhals as nw
|
| 1099 |
+
>>>
|
| 1100 |
+
>>> df_native = pl.DataFrame({"a": [1, 2], "b": [5, None]})
|
| 1101 |
+
>>> nw.from_native(df_native).select(nw.len())
|
| 1102 |
+
┌──────────────────┐
|
| 1103 |
+
|Narwhals DataFrame|
|
| 1104 |
+
|------------------|
|
| 1105 |
+
| shape: (1, 1) |
|
| 1106 |
+
| ┌─────┐ |
|
| 1107 |
+
| │ len │ |
|
| 1108 |
+
| │ --- │ |
|
| 1109 |
+
| │ u32 │ |
|
| 1110 |
+
| ╞═════╡ |
|
| 1111 |
+
| │ 2 │ |
|
| 1112 |
+
| └─────┘ |
|
| 1113 |
+
└──────────────────┘
|
| 1114 |
+
"""
|
| 1115 |
+
return Expr(ExprNode(ExprKind.AGGREGATION, "len"))
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
def sum(*columns: str) -> Expr:
|
| 1119 |
+
"""Sum all values.
|
| 1120 |
+
|
| 1121 |
+
Note:
|
| 1122 |
+
Syntactic sugar for ``nw.col(columns).sum()``
|
| 1123 |
+
|
| 1124 |
+
Arguments:
|
| 1125 |
+
columns: Name(s) of the columns to use in the aggregation function
|
| 1126 |
+
|
| 1127 |
+
Examples:
|
| 1128 |
+
>>> import pandas as pd
|
| 1129 |
+
>>> import narwhals as nw
|
| 1130 |
+
>>>
|
| 1131 |
+
>>> df_native = pd.DataFrame({"a": [1, 2], "b": [-1.4, 6.2]})
|
| 1132 |
+
>>> nw.from_native(df_native).select(nw.sum("a", "b"))
|
| 1133 |
+
┌──────────────────┐
|
| 1134 |
+
|Narwhals DataFrame|
|
| 1135 |
+
|------------------|
|
| 1136 |
+
| a b |
|
| 1137 |
+
| 0 3 4.8 |
|
| 1138 |
+
└──────────────────┘
|
| 1139 |
+
"""
|
| 1140 |
+
return col(*columns).sum()
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
def mean(*columns: str) -> Expr:
|
| 1144 |
+
"""Get the mean value.
|
| 1145 |
+
|
| 1146 |
+
Note:
|
| 1147 |
+
Syntactic sugar for ``nw.col(columns).mean()``
|
| 1148 |
+
|
| 1149 |
+
Arguments:
|
| 1150 |
+
columns: Name(s) of the columns to use in the aggregation function
|
| 1151 |
+
|
| 1152 |
+
Examples:
|
| 1153 |
+
>>> import pyarrow as pa
|
| 1154 |
+
>>> import narwhals as nw
|
| 1155 |
+
>>>
|
| 1156 |
+
>>> df_native = pa.table({"a": [1, 8, 3], "b": [3.14, 6.28, 42.1]})
|
| 1157 |
+
>>> nw.from_native(df_native).select(nw.mean("a", "b"))
|
| 1158 |
+
┌─────────────────────────┐
|
| 1159 |
+
| Narwhals DataFrame |
|
| 1160 |
+
|-------------------------|
|
| 1161 |
+
|pyarrow.Table |
|
| 1162 |
+
|a: double |
|
| 1163 |
+
|b: double |
|
| 1164 |
+
|---- |
|
| 1165 |
+
|a: [[4]] |
|
| 1166 |
+
|b: [[17.173333333333336]]|
|
| 1167 |
+
└─────────────────────────┘
|
| 1168 |
+
"""
|
| 1169 |
+
return col(*columns).mean()
|
| 1170 |
+
|
| 1171 |
+
|
| 1172 |
+
def median(*columns: str) -> Expr:
|
| 1173 |
+
"""Get the median value.
|
| 1174 |
+
|
| 1175 |
+
Notes:
|
| 1176 |
+
- Syntactic sugar for ``nw.col(columns).median()``
|
| 1177 |
+
- Results might slightly differ across backends due to differences in the
|
| 1178 |
+
underlying algorithms used to compute the median.
|
| 1179 |
+
|
| 1180 |
+
Arguments:
|
| 1181 |
+
columns: Name(s) of the columns to use in the aggregation function
|
| 1182 |
+
|
| 1183 |
+
Examples:
|
| 1184 |
+
>>> import polars as pl
|
| 1185 |
+
>>> import narwhals as nw
|
| 1186 |
+
>>>
|
| 1187 |
+
>>> df_native = pl.DataFrame({"a": [4, 5, 2]})
|
| 1188 |
+
>>> nw.from_native(df_native).select(nw.median("a"))
|
| 1189 |
+
┌──────────────────┐
|
| 1190 |
+
|Narwhals DataFrame|
|
| 1191 |
+
|------------------|
|
| 1192 |
+
| shape: (1, 1) |
|
| 1193 |
+
| ┌─────┐ |
|
| 1194 |
+
| │ a │ |
|
| 1195 |
+
| │ --- │ |
|
| 1196 |
+
| │ f64 │ |
|
| 1197 |
+
| ╞═════╡ |
|
| 1198 |
+
| │ 4.0 │ |
|
| 1199 |
+
| └─────┘ |
|
| 1200 |
+
└──────────────────┘
|
| 1201 |
+
"""
|
| 1202 |
+
return col(*columns).median()
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
def min(*columns: str) -> Expr:
|
| 1206 |
+
"""Return the minimum value.
|
| 1207 |
+
|
| 1208 |
+
Note:
|
| 1209 |
+
Syntactic sugar for ``nw.col(columns).min()``.
|
| 1210 |
+
|
| 1211 |
+
Arguments:
|
| 1212 |
+
columns: Name(s) of the columns to use in the aggregation function.
|
| 1213 |
+
|
| 1214 |
+
Examples:
|
| 1215 |
+
>>> import pyarrow as pa
|
| 1216 |
+
>>> import narwhals as nw
|
| 1217 |
+
>>>
|
| 1218 |
+
>>> df_native = pa.table({"a": [1, 2], "b": [5, 10]})
|
| 1219 |
+
>>> nw.from_native(df_native).select(nw.min("a", "b"))
|
| 1220 |
+
┌──────────────────┐
|
| 1221 |
+
|Narwhals DataFrame|
|
| 1222 |
+
|------------------|
|
| 1223 |
+
| pyarrow.Table |
|
| 1224 |
+
| a: int64 |
|
| 1225 |
+
| b: int64 |
|
| 1226 |
+
| ---- |
|
| 1227 |
+
| a: [[1]] |
|
| 1228 |
+
| b: [[5]] |
|
| 1229 |
+
└──────────────────┘
|
| 1230 |
+
"""
|
| 1231 |
+
return col(*columns).min()
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
def max(*columns: str) -> Expr:
|
| 1235 |
+
"""Return the maximum value.
|
| 1236 |
+
|
| 1237 |
+
Note:
|
| 1238 |
+
Syntactic sugar for ``nw.col(columns).max()``.
|
| 1239 |
+
|
| 1240 |
+
Arguments:
|
| 1241 |
+
columns: Name(s) of the columns to use in the aggregation function.
|
| 1242 |
+
|
| 1243 |
+
Examples:
|
| 1244 |
+
>>> import pandas as pd
|
| 1245 |
+
>>> import narwhals as nw
|
| 1246 |
+
>>>
|
| 1247 |
+
>>> df_native = pd.DataFrame({"a": [1, 2], "b": [5, 10]})
|
| 1248 |
+
>>> nw.from_native(df_native).select(nw.max("a", "b"))
|
| 1249 |
+
┌──────────────────┐
|
| 1250 |
+
|Narwhals DataFrame|
|
| 1251 |
+
|------------------|
|
| 1252 |
+
| a b |
|
| 1253 |
+
| 0 2 10 |
|
| 1254 |
+
└──────────────────┘
|
| 1255 |
+
"""
|
| 1256 |
+
return col(*columns).max()
|
| 1257 |
+
|
| 1258 |
+
|
| 1259 |
+
def _expr_with_horizontal_op(name: str, *exprs: IntoExpr, **kwargs: Any) -> Expr:
|
| 1260 |
+
if not exprs:
|
| 1261 |
+
msg = f"At least one expression must be passed to `{name}`"
|
| 1262 |
+
raise ValueError(msg)
|
| 1263 |
+
return Expr(
|
| 1264 |
+
ExprNode(
|
| 1265 |
+
ExprKind.ELEMENTWISE, name, exprs=exprs, **kwargs, allow_multi_output=True
|
| 1266 |
+
)
|
| 1267 |
+
)
|
| 1268 |
+
|
| 1269 |
+
|
| 1270 |
+
def corr(a: IntoExpr, b: IntoExpr, method: CorrelationMethod = "pearson") -> Expr:
|
| 1271 |
+
"""Compute the Pearson's or Spearman rank correlation between two columns.
|
| 1272 |
+
|
| 1273 |
+
Arguments:
|
| 1274 |
+
a: Column name or Expression
|
| 1275 |
+
b: Column name or Expression
|
| 1276 |
+
method: Correlation method ('pearson' or 'spearman')
|
| 1277 |
+
|
| 1278 |
+
Examples:
|
| 1279 |
+
>>> import polars as pl
|
| 1280 |
+
>>> import narwhals as nw
|
| 1281 |
+
>>>
|
| 1282 |
+
>>> df_native = pl.DataFrame({"a": [1, 2, 3], "b": [0, 3, 2]})
|
| 1283 |
+
>>> nw.from_native(df_native).select(
|
| 1284 |
+
... pearson=nw.corr("a", "b", method="pearson"),
|
| 1285 |
+
... spearman=nw.corr("a", "b", method="spearman"),
|
| 1286 |
+
... )
|
| 1287 |
+
┌───────────────────────┐
|
| 1288 |
+
| Narwhals DataFrame |
|
| 1289 |
+
|-----------------------|
|
| 1290 |
+
|shape: (1, 2) |
|
| 1291 |
+
|┌──────────┬──────────┐|
|
| 1292 |
+
|│ pearson ┆ spearman │|
|
| 1293 |
+
|│ --- ┆ --- │|
|
| 1294 |
+
|│ f64 ┆ f64 │|
|
| 1295 |
+
|╞══════════╪══════════╡|
|
| 1296 |
+
|│ 0.654654 ┆ 0.5 │|
|
| 1297 |
+
|└──────────┴──────────┘|
|
| 1298 |
+
└───────────────────────┘
|
| 1299 |
+
"""
|
| 1300 |
+
return Expr(ExprNode(ExprKind.AGGREGATION, "corr", exprs=(a, b), method=method))
|
| 1301 |
+
|
| 1302 |
+
|
| 1303 |
+
def sum_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr:
|
| 1304 |
+
"""Sum all values horizontally across columns.
|
| 1305 |
+
|
| 1306 |
+
Warning:
|
| 1307 |
+
Unlike Polars, we support horizontal sum over numeric columns only.
|
| 1308 |
+
|
| 1309 |
+
Arguments:
|
| 1310 |
+
exprs: Name(s) of the columns to use in the aggregation function. Accepts
|
| 1311 |
+
expression input.
|
| 1312 |
+
|
| 1313 |
+
Examples:
|
| 1314 |
+
>>> import polars as pl
|
| 1315 |
+
>>> import narwhals as nw
|
| 1316 |
+
>>>
|
| 1317 |
+
>>> df_native = pl.DataFrame({"a": [1, 2, 3], "b": [5, 10, None]})
|
| 1318 |
+
>>> nw.from_native(df_native).with_columns(sum=nw.sum_horizontal("a", "b"))
|
| 1319 |
+
┌────────────────────┐
|
| 1320 |
+
| Narwhals DataFrame |
|
| 1321 |
+
|--------------------|
|
| 1322 |
+
|shape: (3, 3) |
|
| 1323 |
+
|┌─────┬──────┬─────┐|
|
| 1324 |
+
|│ a ┆ b ┆ sum │|
|
| 1325 |
+
|│ --- ┆ --- ┆ --- │|
|
| 1326 |
+
|│ i64 ┆ i64 ┆ i64 │|
|
| 1327 |
+
|╞═════╪══════╪═════╡|
|
| 1328 |
+
|│ 1 ┆ 5 ┆ 6 │|
|
| 1329 |
+
|│ 2 ┆ 10 ┆ 12 │|
|
| 1330 |
+
|│ 3 ┆ null ┆ 3 │|
|
| 1331 |
+
|└─────┴──────┴─────┘|
|
| 1332 |
+
└────────────────────┘
|
| 1333 |
+
"""
|
| 1334 |
+
return _expr_with_horizontal_op("sum_horizontal", *flatten(exprs))
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
def min_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr:
|
| 1338 |
+
"""Get the minimum value horizontally across columns.
|
| 1339 |
+
|
| 1340 |
+
Notes:
|
| 1341 |
+
We support `min_horizontal` over numeric columns only.
|
| 1342 |
+
|
| 1343 |
+
Arguments:
|
| 1344 |
+
exprs: Name(s) of the columns to use in the aggregation function. Accepts
|
| 1345 |
+
expression input.
|
| 1346 |
+
|
| 1347 |
+
Examples:
|
| 1348 |
+
>>> import pyarrow as pa
|
| 1349 |
+
>>> import narwhals as nw
|
| 1350 |
+
>>>
|
| 1351 |
+
>>> df_native = pa.table({"a": [1, 8, 3], "b": [4, 5, None]})
|
| 1352 |
+
>>> nw.from_native(df_native).with_columns(h_min=nw.min_horizontal("a", "b"))
|
| 1353 |
+
┌──────────────────┐
|
| 1354 |
+
|Narwhals DataFrame|
|
| 1355 |
+
|------------------|
|
| 1356 |
+
| pyarrow.Table |
|
| 1357 |
+
| a: int64 |
|
| 1358 |
+
| b: int64 |
|
| 1359 |
+
| h_min: int64 |
|
| 1360 |
+
| ---- |
|
| 1361 |
+
| a: [[1,8,3]] |
|
| 1362 |
+
| b: [[4,5,null]] |
|
| 1363 |
+
| h_min: [[1,5,3]] |
|
| 1364 |
+
└──────────────────┘
|
| 1365 |
+
"""
|
| 1366 |
+
return _expr_with_horizontal_op("min_horizontal", *flatten(exprs))
|
| 1367 |
+
|
| 1368 |
+
|
| 1369 |
+
def max_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr:
|
| 1370 |
+
"""Get the maximum value horizontally across columns.
|
| 1371 |
+
|
| 1372 |
+
Notes:
|
| 1373 |
+
We support `max_horizontal` over numeric columns only.
|
| 1374 |
+
|
| 1375 |
+
Arguments:
|
| 1376 |
+
exprs: Name(s) of the columns to use in the aggregation function. Accepts
|
| 1377 |
+
expression input.
|
| 1378 |
+
|
| 1379 |
+
Examples:
|
| 1380 |
+
>>> import polars as pl
|
| 1381 |
+
>>> import narwhals as nw
|
| 1382 |
+
>>>
|
| 1383 |
+
>>> df_native = pl.DataFrame({"a": [1, 8, 3], "b": [4, 5, None]})
|
| 1384 |
+
>>> nw.from_native(df_native).with_columns(h_max=nw.max_horizontal("a", "b"))
|
| 1385 |
+
┌──────────────────────┐
|
| 1386 |
+
| Narwhals DataFrame |
|
| 1387 |
+
|----------------------|
|
| 1388 |
+
|shape: (3, 3) |
|
| 1389 |
+
|┌─────┬──────┬───────┐|
|
| 1390 |
+
|│ a ┆ b ┆ h_max │|
|
| 1391 |
+
|│ --- ┆ --- ┆ --- │|
|
| 1392 |
+
|│ i64 ┆ i64 ┆ i64 │|
|
| 1393 |
+
|╞═════╪══════╪═══════╡|
|
| 1394 |
+
|│ 1 ┆ 4 ┆ 4 │|
|
| 1395 |
+
|│ 8 ┆ 5 ┆ 8 │|
|
| 1396 |
+
|│ 3 ┆ null ┆ 3 │|
|
| 1397 |
+
|└─────┴──────┴───────┘|
|
| 1398 |
+
└──────────────────────┘
|
| 1399 |
+
"""
|
| 1400 |
+
return _expr_with_horizontal_op("max_horizontal", *flatten(exprs))
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
class When:
|
| 1404 |
+
def __init__(self, *predicates: IntoExpr | Iterable[IntoExpr]) -> None:
|
| 1405 |
+
self._predicate = all_horizontal(*flatten(predicates), ignore_nulls=False)
|
| 1406 |
+
|
| 1407 |
+
def then(self, value: IntoExpr | NonNestedLiteral) -> Then:
|
| 1408 |
+
return Then(
|
| 1409 |
+
ExprNode(
|
| 1410 |
+
ExprKind.ELEMENTWISE,
|
| 1411 |
+
"when_then",
|
| 1412 |
+
exprs=(self._predicate, value),
|
| 1413 |
+
allow_multi_output=False,
|
| 1414 |
+
)
|
| 1415 |
+
)
|
| 1416 |
+
|
| 1417 |
+
|
| 1418 |
+
class Then(Expr):
|
| 1419 |
+
def otherwise(self, value: IntoExpr | NonNestedLiteral) -> Expr:
|
| 1420 |
+
node = self._nodes[0]
|
| 1421 |
+
return Expr(
|
| 1422 |
+
ExprNode(ExprKind.ELEMENTWISE, "when_then", exprs=(*node.exprs, value))
|
| 1423 |
+
)
|
| 1424 |
+
|
| 1425 |
+
|
| 1426 |
+
def when(*predicates: IntoExpr | Iterable[IntoExpr]) -> When:
|
| 1427 |
+
"""Start a `when-then-otherwise` expression.
|
| 1428 |
+
|
| 1429 |
+
Expression similar to an `if-else` statement in Python. Always initiated by a
|
| 1430 |
+
`pl.when(<condition>).then(<value if condition>)`, and optionally followed by a
|
| 1431 |
+
`.otherwise(<value if condition is false>)` can be appended at the end. If not
|
| 1432 |
+
appended, and the condition is not `True`, `None` will be returned.
|
| 1433 |
+
|
| 1434 |
+
Info:
|
| 1435 |
+
Chaining multiple `.when(<condition>).then(<value>)` statements is currently
|
| 1436 |
+
not supported.
|
| 1437 |
+
See [Narwhals#668](https://github.com/narwhals-dev/narwhals/issues/668).
|
| 1438 |
+
|
| 1439 |
+
Arguments:
|
| 1440 |
+
predicates: Condition(s) that must be met in order to apply the subsequent
|
| 1441 |
+
statement. Accepts one or more boolean expressions, which are implicitly
|
| 1442 |
+
combined with `&`. String input is parsed as a column name.
|
| 1443 |
+
|
| 1444 |
+
Returns:
|
| 1445 |
+
A "when" object, which `.then` can be called on.
|
| 1446 |
+
|
| 1447 |
+
Examples:
|
| 1448 |
+
>>> import pandas as pd
|
| 1449 |
+
>>> import narwhals as nw
|
| 1450 |
+
>>>
|
| 1451 |
+
>>> data = {"a": [1, 2, 3], "b": [5, 10, 15]}
|
| 1452 |
+
>>> df_native = pd.DataFrame(data)
|
| 1453 |
+
>>> nw.from_native(df_native).with_columns(
|
| 1454 |
+
... nw.when(nw.col("a") < 3).then(5).otherwise(6).alias("a_when")
|
| 1455 |
+
... )
|
| 1456 |
+
┌──────────────────┐
|
| 1457 |
+
|Narwhals DataFrame|
|
| 1458 |
+
|------------------|
|
| 1459 |
+
| a b a_when |
|
| 1460 |
+
| 0 1 5 5 |
|
| 1461 |
+
| 1 2 10 5 |
|
| 1462 |
+
| 2 3 15 6 |
|
| 1463 |
+
└──────────────────┘
|
| 1464 |
+
"""
|
| 1465 |
+
return When(*predicates)
|
| 1466 |
+
|
| 1467 |
+
|
| 1468 |
+
def all_horizontal(*exprs: IntoExpr | Iterable[IntoExpr], ignore_nulls: bool) -> Expr:
|
| 1469 |
+
r"""Compute the bitwise AND horizontally across columns.
|
| 1470 |
+
|
| 1471 |
+
Arguments:
|
| 1472 |
+
exprs: Name(s) of the columns to use in the aggregation function. Accepts
|
| 1473 |
+
expression input.
|
| 1474 |
+
ignore_nulls: Whether to ignore nulls:
|
| 1475 |
+
|
| 1476 |
+
- If `True`, null values are ignored. If there are no elements, the result
|
| 1477 |
+
is `True`.
|
| 1478 |
+
- If `False`, Kleene logic is followed. Note that this is not allowed for
|
| 1479 |
+
pandas with classical NumPy dtypes when null values are present.
|
| 1480 |
+
|
| 1481 |
+
Examples:
|
| 1482 |
+
>>> import pyarrow as pa
|
| 1483 |
+
>>> import narwhals as nw
|
| 1484 |
+
>>>
|
| 1485 |
+
>>> data = {
|
| 1486 |
+
... "a": [False, False, True, True, False, None],
|
| 1487 |
+
... "b": [False, True, True, None, None, None],
|
| 1488 |
+
... }
|
| 1489 |
+
>>> df_native = pa.table(data)
|
| 1490 |
+
>>> nw.from_native(df_native).select(
|
| 1491 |
+
... "a", "b", all=nw.all_horizontal("a", "b", ignore_nulls=False)
|
| 1492 |
+
... )
|
| 1493 |
+
┌─────────────────────────────────────────┐
|
| 1494 |
+
| Narwhals DataFrame |
|
| 1495 |
+
|-----------------------------------------|
|
| 1496 |
+
|pyarrow.Table |
|
| 1497 |
+
|a: bool |
|
| 1498 |
+
|b: bool |
|
| 1499 |
+
|all: bool |
|
| 1500 |
+
|---- |
|
| 1501 |
+
|a: [[false,false,true,true,false,null]] |
|
| 1502 |
+
|b: [[false,true,true,null,null,null]] |
|
| 1503 |
+
|all: [[false,false,true,null,false,null]]|
|
| 1504 |
+
└─────────────────────────────────────────┘
|
| 1505 |
+
"""
|
| 1506 |
+
return _expr_with_horizontal_op(
|
| 1507 |
+
"all_horizontal", *flatten(exprs), ignore_nulls=ignore_nulls
|
| 1508 |
+
)
|
| 1509 |
+
|
| 1510 |
+
|
| 1511 |
+
def lit(value: PythonLiteral, dtype: IntoDType | None = None) -> Expr:
|
| 1512 |
+
"""Return an expression representing a literal value.
|
| 1513 |
+
|
| 1514 |
+
Arguments:
|
| 1515 |
+
value: The value to use as literal. Can be a scalar value, list, tuple, or dict.
|
| 1516 |
+
Lists and tuples are converted to `List` dtype, dicts to `Struct` dtype.
|
| 1517 |
+
dtype: The data type of the literal value. If not provided, the data type will
|
| 1518 |
+
be inferred by the native library. For empty lists/dicts, dtype must be
|
| 1519 |
+
specified explicitly.
|
| 1520 |
+
|
| 1521 |
+
Examples:
|
| 1522 |
+
Scalar literals:
|
| 1523 |
+
|
| 1524 |
+
>>> import pyarrow as pa
|
| 1525 |
+
>>> import narwhals as nw
|
| 1526 |
+
>>>
|
| 1527 |
+
>>> df_nw = nw.from_native(pa.table({"a": [1, 2]}))
|
| 1528 |
+
>>> df_nw.with_columns(nw.lit(3))
|
| 1529 |
+
┌──────────────────┐
|
| 1530 |
+
|Narwhals DataFrame|
|
| 1531 |
+
|------------------|
|
| 1532 |
+
| pyarrow.Table |
|
| 1533 |
+
| a: int64 |
|
| 1534 |
+
| literal: int64 |
|
| 1535 |
+
| ---- |
|
| 1536 |
+
| a: [[1,2]] |
|
| 1537 |
+
| literal: [[3,3]] |
|
| 1538 |
+
└──────────────────┘
|
| 1539 |
+
|
| 1540 |
+
List literals (creates a List column):
|
| 1541 |
+
|
| 1542 |
+
>>> df_nw.with_columns(nw.lit([1, 2, 3]).alias("list_col"))
|
| 1543 |
+
┌─────────────────────────────┐
|
| 1544 |
+
| Narwhals DataFrame |
|
| 1545 |
+
|-----------------------------|
|
| 1546 |
+
|pyarrow.Table |
|
| 1547 |
+
|a: int64 |
|
| 1548 |
+
|list_col: list<item: int64> |
|
| 1549 |
+
| child 0, item: int64 |
|
| 1550 |
+
|---- |
|
| 1551 |
+
|a: [[1,2]] |
|
| 1552 |
+
|list_col: [[[1,2,3],[1,2,3]]]|
|
| 1553 |
+
└─────────────────────────────┘
|
| 1554 |
+
|
| 1555 |
+
Dict literals (creates a Struct column):
|
| 1556 |
+
|
| 1557 |
+
>>> df_nw.with_columns(nw.lit({"x": 1, "y": 2}).alias("struct_col"))
|
| 1558 |
+
┌──────────────────────────────────────┐
|
| 1559 |
+
| Narwhals DataFrame |
|
| 1560 |
+
|--------------------------------------|
|
| 1561 |
+
|pyarrow.Table |
|
| 1562 |
+
|a: int64 |
|
| 1563 |
+
|struct_col: struct<x: int64, y: int64>|
|
| 1564 |
+
| child 0, x: int64 |
|
| 1565 |
+
| child 1, y: int64 |
|
| 1566 |
+
|---- |
|
| 1567 |
+
|a: [[1,2]] |
|
| 1568 |
+
|struct_col: [ |
|
| 1569 |
+
| -- is_valid: all not null |
|
| 1570 |
+
| -- child 0 type: int64 |
|
| 1571 |
+
|[1,1] |
|
| 1572 |
+
| -- child 1 type: int64 |
|
| 1573 |
+
|[2,2]] |
|
| 1574 |
+
└──────────────────────────────────────┘
|
| 1575 |
+
"""
|
| 1576 |
+
if is_numpy_array(value):
|
| 1577 |
+
msg = (
|
| 1578 |
+
"numpy arrays are not supported as literal values. "
|
| 1579 |
+
"Consider using `with_columns` to create a new column from the array."
|
| 1580 |
+
)
|
| 1581 |
+
raise ValueError(msg)
|
| 1582 |
+
if is_nested_literal(value):
|
| 1583 |
+
if not value:
|
| 1584 |
+
if not dtype:
|
| 1585 |
+
msg = "Cannot infer dtype for empty nested structure. Please provide an explicit dtype parameter."
|
| 1586 |
+
raise ValueError(msg)
|
| 1587 |
+
elif isinstance(value, dict):
|
| 1588 |
+
if any(is_nested_literal(v) for v in value.values()):
|
| 1589 |
+
msg = "Nested structures with nested values are not supported."
|
| 1590 |
+
raise NotImplementedError(msg)
|
| 1591 |
+
elif is_nested_literal(value[0]):
|
| 1592 |
+
msg = "Nested structures with nested values are not supported."
|
| 1593 |
+
raise NotImplementedError(msg)
|
| 1594 |
+
return Expr(ExprNode(ExprKind.LITERAL, "lit", value=value, dtype=dtype))
|
| 1595 |
+
|
| 1596 |
+
|
| 1597 |
+
def any_horizontal(*exprs: IntoExpr | Iterable[IntoExpr], ignore_nulls: bool) -> Expr:
|
| 1598 |
+
r"""Compute the bitwise OR horizontally across columns.
|
| 1599 |
+
|
| 1600 |
+
Arguments:
|
| 1601 |
+
exprs: Name(s) of the columns to use in the aggregation function. Accepts
|
| 1602 |
+
expression input.
|
| 1603 |
+
ignore_nulls: Whether to ignore nulls:
|
| 1604 |
+
|
| 1605 |
+
- If `True`, null values are ignored. If there are no elements, the result
|
| 1606 |
+
is `False`.
|
| 1607 |
+
- If `False`, Kleene logic is followed. Note that this is not allowed for
|
| 1608 |
+
pandas with classical NumPy dtypes when null values are present.
|
| 1609 |
+
|
| 1610 |
+
Examples:
|
| 1611 |
+
>>> import polars as pl
|
| 1612 |
+
>>> import narwhals as nw
|
| 1613 |
+
>>>
|
| 1614 |
+
>>> data = {
|
| 1615 |
+
... "a": [False, False, True, True, False, None],
|
| 1616 |
+
... "b": [False, True, True, None, None, None],
|
| 1617 |
+
... }
|
| 1618 |
+
>>> df_native = pl.DataFrame(data)
|
| 1619 |
+
>>> nw.from_native(df_native).select(
|
| 1620 |
+
... "a", "b", any=nw.any_horizontal("a", "b", ignore_nulls=False)
|
| 1621 |
+
... )
|
| 1622 |
+
┌─────────────────────────┐
|
| 1623 |
+
| Narwhals DataFrame |
|
| 1624 |
+
|-------------------------|
|
| 1625 |
+
|shape: (6, 3) |
|
| 1626 |
+
|┌───────┬───────┬───────┐|
|
| 1627 |
+
|│ a ┆ b ┆ any │|
|
| 1628 |
+
|│ --- ┆ --- ┆ --- │|
|
| 1629 |
+
|│ bool ┆ bool ┆ bool │|
|
| 1630 |
+
|╞═══════╪═══════╪═══════╡|
|
| 1631 |
+
|│ false ┆ false ┆ false │|
|
| 1632 |
+
|│ false ┆ true ┆ true │|
|
| 1633 |
+
|│ true ┆ true ┆ true │|
|
| 1634 |
+
|│ true ┆ null ┆ true │|
|
| 1635 |
+
|│ false ┆ null ┆ null │|
|
| 1636 |
+
|│ null ┆ null ┆ null │|
|
| 1637 |
+
|└───────┴───────┴───────┘|
|
| 1638 |
+
└─────────────────────────┘
|
| 1639 |
+
"""
|
| 1640 |
+
return _expr_with_horizontal_op(
|
| 1641 |
+
"any_horizontal", *flatten(exprs), ignore_nulls=ignore_nulls
|
| 1642 |
+
)
|
| 1643 |
+
|
| 1644 |
+
|
| 1645 |
+
def mean_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr:
|
| 1646 |
+
"""Compute the mean of all values horizontally across columns.
|
| 1647 |
+
|
| 1648 |
+
Arguments:
|
| 1649 |
+
exprs: Name(s) of the columns to use in the aggregation function. Accepts
|
| 1650 |
+
expression input.
|
| 1651 |
+
|
| 1652 |
+
Examples:
|
| 1653 |
+
>>> import pyarrow as pa
|
| 1654 |
+
>>> import narwhals as nw
|
| 1655 |
+
>>>
|
| 1656 |
+
>>> data = {"a": [1, 8, 3], "b": [4, 5, None], "c": ["x", "y", "z"]}
|
| 1657 |
+
>>> df_native = pa.table(data)
|
| 1658 |
+
|
| 1659 |
+
We define a dataframe-agnostic function that computes the horizontal mean of "a"
|
| 1660 |
+
and "b" columns:
|
| 1661 |
+
|
| 1662 |
+
>>> nw.from_native(df_native).select(nw.mean_horizontal("a", "b"))
|
| 1663 |
+
┌──────────────────┐
|
| 1664 |
+
|Narwhals DataFrame|
|
| 1665 |
+
|------------------|
|
| 1666 |
+
| pyarrow.Table |
|
| 1667 |
+
| a: double |
|
| 1668 |
+
| ---- |
|
| 1669 |
+
| a: [[2.5,6.5,3]] |
|
| 1670 |
+
└──────────────────┘
|
| 1671 |
+
"""
|
| 1672 |
+
return _expr_with_horizontal_op("mean_horizontal", *flatten(exprs))
|
| 1673 |
+
|
| 1674 |
+
|
| 1675 |
+
def concat_str(
|
| 1676 |
+
exprs: IntoExpr | Iterable[IntoExpr],
|
| 1677 |
+
*more_exprs: IntoExpr,
|
| 1678 |
+
separator: str = "",
|
| 1679 |
+
ignore_nulls: bool = False,
|
| 1680 |
+
) -> Expr:
|
| 1681 |
+
r"""Horizontally concatenate columns into a single string column.
|
| 1682 |
+
|
| 1683 |
+
Arguments:
|
| 1684 |
+
exprs: Columns to concatenate into a single string column. Accepts expression
|
| 1685 |
+
input. Strings are parsed as column names, other non-expression inputs are
|
| 1686 |
+
parsed as literals. Non-`String` columns are cast to `String`.
|
| 1687 |
+
*more_exprs: Additional columns to concatenate into a single string column,
|
| 1688 |
+
specified as positional arguments.
|
| 1689 |
+
separator: String that will be used to separate the values of each column.
|
| 1690 |
+
ignore_nulls: Ignore null values (default is `False`).
|
| 1691 |
+
If set to `False`, null values will be propagated and if the row contains any
|
| 1692 |
+
null values, the output is null.
|
| 1693 |
+
|
| 1694 |
+
Examples:
|
| 1695 |
+
>>> import pandas as pd
|
| 1696 |
+
>>> import narwhals as nw
|
| 1697 |
+
>>>
|
| 1698 |
+
>>> data = {
|
| 1699 |
+
... "a": [1, 2, 3],
|
| 1700 |
+
... "b": ["dogs", "cats", None],
|
| 1701 |
+
... "c": ["play", "swim", "walk"],
|
| 1702 |
+
... }
|
| 1703 |
+
>>> df_native = pd.DataFrame(data)
|
| 1704 |
+
>>> (
|
| 1705 |
+
... nw.from_native(df_native).select(
|
| 1706 |
+
... nw.concat_str(
|
| 1707 |
+
... [nw.col("a") * 2, nw.col("b"), nw.col("c")], separator=" "
|
| 1708 |
+
... ).alias("full_sentence")
|
| 1709 |
+
... )
|
| 1710 |
+
... )
|
| 1711 |
+
┌──────────────────┐
|
| 1712 |
+
|Narwhals DataFrame|
|
| 1713 |
+
|------------------|
|
| 1714 |
+
| full_sentence |
|
| 1715 |
+
| 0 2 dogs play |
|
| 1716 |
+
| 1 4 cats swim |
|
| 1717 |
+
| 2 NaN |
|
| 1718 |
+
└──────────────────┘
|
| 1719 |
+
"""
|
| 1720 |
+
flat_exprs = flatten([*flatten([exprs]), *more_exprs])
|
| 1721 |
+
return _expr_with_horizontal_op(
|
| 1722 |
+
"concat_str", *flat_exprs, separator=separator, ignore_nulls=ignore_nulls
|
| 1723 |
+
)
|
| 1724 |
+
|
| 1725 |
+
|
| 1726 |
+
def coalesce(
|
| 1727 |
+
exprs: IntoExpr | Iterable[IntoExpr], *more_exprs: IntoExpr | NonNestedLiteral
|
| 1728 |
+
) -> Expr:
|
| 1729 |
+
"""Folds the columns from left to right, keeping the first non-null value.
|
| 1730 |
+
|
| 1731 |
+
Arguments:
|
| 1732 |
+
exprs: Columns to coalesce, must be a str, nw.Expr, or nw.Series
|
| 1733 |
+
where strings are parsed as column names and both nw.Expr/nw.Series
|
| 1734 |
+
are passed through as-is. Scalar values must be wrapped in `nw.lit`.
|
| 1735 |
+
|
| 1736 |
+
*more_exprs: Additional columns to coalesce, specified as positional arguments.
|
| 1737 |
+
|
| 1738 |
+
Raises:
|
| 1739 |
+
TypeError: If any of the inputs are not a str, nw.Expr, or nw.Series.
|
| 1740 |
+
|
| 1741 |
+
Examples:
|
| 1742 |
+
>>> import polars as pl
|
| 1743 |
+
>>> import narwhals as nw
|
| 1744 |
+
>>> data = [
|
| 1745 |
+
... (1, 5, None),
|
| 1746 |
+
... (None, 6, None),
|
| 1747 |
+
... (None, None, 9),
|
| 1748 |
+
... (4, 8, 10),
|
| 1749 |
+
... (None, None, None),
|
| 1750 |
+
... ]
|
| 1751 |
+
>>> df = pl.DataFrame(data, schema=["a", "b", "c"], orient="row")
|
| 1752 |
+
>>> nw.from_native(df).select(nw.coalesce("a", "b", "c", nw.lit(-1)))
|
| 1753 |
+
┌──────────────────┐
|
| 1754 |
+
|Narwhals DataFrame|
|
| 1755 |
+
|------------------|
|
| 1756 |
+
| shape: (5, 1) |
|
| 1757 |
+
| ┌─────┐ |
|
| 1758 |
+
| │ a │ |
|
| 1759 |
+
| │ --- │ |
|
| 1760 |
+
| │ i64 │ |
|
| 1761 |
+
| ╞═════╡ |
|
| 1762 |
+
| │ 1 │ |
|
| 1763 |
+
| │ 6 │ |
|
| 1764 |
+
| │ 9 │ |
|
| 1765 |
+
| │ 4 │ |
|
| 1766 |
+
| │ -1 │ |
|
| 1767 |
+
| └─────┘ |
|
| 1768 |
+
└──────────────────┘
|
| 1769 |
+
"""
|
| 1770 |
+
flat_exprs = flatten([*flatten([exprs]), *more_exprs])
|
| 1771 |
+
|
| 1772 |
+
non_exprs = [
|
| 1773 |
+
expr
|
| 1774 |
+
for expr in flat_exprs
|
| 1775 |
+
if not (isinstance(expr, str) or is_expr(expr) or is_series(expr))
|
| 1776 |
+
]
|
| 1777 |
+
if non_exprs:
|
| 1778 |
+
msg = (
|
| 1779 |
+
f"All arguments to `coalesce` must be of type {str!r}, Expr, or Series."
|
| 1780 |
+
"\nGot the following invalid arguments (type, value):"
|
| 1781 |
+
f"\n {', '.join(repr((type(e), e)) for e in non_exprs)}"
|
| 1782 |
+
)
|
| 1783 |
+
raise TypeError(msg)
|
| 1784 |
+
|
| 1785 |
+
return Expr(
|
| 1786 |
+
ExprNode(
|
| 1787 |
+
ExprKind.ELEMENTWISE, "coalesce", exprs=flat_exprs, allow_multi_output=True
|
| 1788 |
+
)
|
| 1789 |
+
)
|
| 1790 |
+
|
| 1791 |
+
|
| 1792 |
+
def format(f_string: str, *args: IntoExpr) -> Expr:
|
| 1793 |
+
"""Format expressions as a string.
|
| 1794 |
+
|
| 1795 |
+
Arguments:
|
| 1796 |
+
f_string: A string that with placeholders.
|
| 1797 |
+
args: Expression(s) that fill the placeholders.
|
| 1798 |
+
|
| 1799 |
+
Examples:
|
| 1800 |
+
>>> import duckdb
|
| 1801 |
+
>>> import narwhals as nw
|
| 1802 |
+
>>> rel = duckdb.sql("select * from values ('a', 1), ('b', 2), ('c', 3) df(a, b)")
|
| 1803 |
+
>>> df = nw.from_native(rel)
|
| 1804 |
+
>>> df.with_columns(formatted=nw.format("foo_{}_bar_{}", nw.col("a"), "b"))
|
| 1805 |
+
┌─────────────────────────────────┐
|
| 1806 |
+
| Narwhals LazyFrame |
|
| 1807 |
+
|---------------------------------|
|
| 1808 |
+
|┌─────────┬───────┬─────────────┐|
|
| 1809 |
+
|│ a │ b │ formatted │|
|
| 1810 |
+
|│ varchar │ int32 │ varchar │|
|
| 1811 |
+
|├─────────┼───────┼─────────────┤|
|
| 1812 |
+
|│ a │ 1 │ foo_a_bar_1 │|
|
| 1813 |
+
|│ b │ 2 │ foo_b_bar_2 │|
|
| 1814 |
+
|│ c │ 3 │ foo_c_bar_3 │|
|
| 1815 |
+
|└─────────┴───────┴─────────────┘|
|
| 1816 |
+
└─────────────────────────────────┘
|
| 1817 |
+
"""
|
| 1818 |
+
if (n_placeholders := f_string.count("{}")) != len(args):
|
| 1819 |
+
msg = f"number of placeholders should equal the number of arguments. Expected {n_placeholders} arguments, got {len(args)}."
|
| 1820 |
+
raise ValueError(msg)
|
| 1821 |
+
|
| 1822 |
+
exprs = []
|
| 1823 |
+
it = iter(args)
|
| 1824 |
+
for i, s in enumerate(f_string.split("{}")):
|
| 1825 |
+
if i > 0:
|
| 1826 |
+
exprs.append(next(it))
|
| 1827 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
| 4 |
+
|
| 5 |
+
from narwhals._expression_parsing import is_scalar_like
|
| 6 |
+
from narwhals._utils import tupleify
|
| 7 |
+
from narwhals.exceptions import InvalidOperationError
|
| 8 |
+
from narwhals.typing import DataFrameT
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from collections.abc import Iterable, Iterator, Sequence
|
| 12 |
+
|
| 13 |
+
from narwhals._compliant.typing import CompliantExprAny
|
| 14 |
+
from narwhals.dataframe import LazyFrame
|
| 15 |
+
from narwhals.expr import Expr
|
| 16 |
+
|
| 17 |
+
LazyFrameT = TypeVar("LazyFrameT", bound="LazyFrame[Any]")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class GroupBy(Generic[DataFrameT]):
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
df: DataFrameT,
|
| 24 |
+
keys: Sequence[str] | Sequence[CompliantExprAny],
|
| 25 |
+
/,
|
| 26 |
+
*,
|
| 27 |
+
drop_null_keys: bool,
|
| 28 |
+
) -> None:
|
| 29 |
+
self._df: DataFrameT = df
|
| 30 |
+
self._keys = keys
|
| 31 |
+
self._grouped = self._df._compliant_frame.group_by(
|
| 32 |
+
self._keys, drop_null_keys=drop_null_keys
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def agg(self, *aggs: Expr | Iterable[Expr], **named_aggs: Expr) -> DataFrameT:
|
| 36 |
+
"""Compute aggregations for each group of a group by operation.
|
| 37 |
+
|
| 38 |
+
Arguments:
|
| 39 |
+
aggs: Aggregations to compute for each group of the group by operation,
|
| 40 |
+
specified as positional arguments.
|
| 41 |
+
named_aggs: Additional aggregations, specified as keyword arguments.
|
| 42 |
+
|
| 43 |
+
Examples:
|
| 44 |
+
Group by one column or by multiple columns and call `agg` to compute
|
| 45 |
+
the grouped sum of another column.
|
| 46 |
+
|
| 47 |
+
>>> import pandas as pd
|
| 48 |
+
>>> import narwhals as nw
|
| 49 |
+
>>> df_native = pd.DataFrame(
|
| 50 |
+
... {
|
| 51 |
+
... "a": ["a", "b", "a", "b", "c"],
|
| 52 |
+
... "b": [1, 2, 1, 3, 3],
|
| 53 |
+
... "c": [5, 4, 3, 2, 1],
|
| 54 |
+
... }
|
| 55 |
+
... )
|
| 56 |
+
>>> df = nw.from_native(df_native)
|
| 57 |
+
>>>
|
| 58 |
+
>>> df.group_by("a").agg(nw.col("b").sum()).sort("a")
|
| 59 |
+
┌──────────────────┐
|
| 60 |
+
|Narwhals DataFrame|
|
| 61 |
+
|------------------|
|
| 62 |
+
| a b |
|
| 63 |
+
| 0 a 2 |
|
| 64 |
+
| 1 b 5 |
|
| 65 |
+
| 2 c 3 |
|
| 66 |
+
└──────────────────┘
|
| 67 |
+
>>>
|
| 68 |
+
>>> df.group_by("a", "b").agg(nw.col("c").sum()).sort("a", "b").to_native()
|
| 69 |
+
a b c
|
| 70 |
+
0 a 1 8
|
| 71 |
+
1 b 2 4
|
| 72 |
+
2 b 3 2
|
| 73 |
+
3 c 3 1
|
| 74 |
+
"""
|
| 75 |
+
compliant_aggs = self._df._flatten_and_extract(*aggs, **named_aggs)
|
| 76 |
+
if not all(is_scalar_like(x) for x in compliant_aggs):
|
| 77 |
+
msg = (
|
| 78 |
+
"Found expression which does not aggregate.\n\n"
|
| 79 |
+
"All expressions passed to GroupBy.agg must aggregate.\n"
|
| 80 |
+
"For example, `df.group_by('a').agg(nw.col('b').sum())` is valid,\n"
|
| 81 |
+
"but `df.group_by('a').agg(nw.col('b'))` is not."
|
| 82 |
+
)
|
| 83 |
+
raise InvalidOperationError(msg)
|
| 84 |
+
return self._df._with_compliant(self._grouped.agg(*compliant_aggs))
|
| 85 |
+
|
| 86 |
+
def __iter__(self) -> Iterator[tuple[Any, DataFrameT]]:
|
| 87 |
+
yield from (
|
| 88 |
+
(tupleify(key), self._df._with_compliant(df))
|
| 89 |
+
for (key, df) in self._grouped.__iter__()
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class LazyGroupBy(Generic[LazyFrameT]):
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
df: LazyFrameT,
|
| 97 |
+
keys: Sequence[str] | Sequence[CompliantExprAny],
|
| 98 |
+
/,
|
| 99 |
+
*,
|
| 100 |
+
drop_null_keys: bool,
|
| 101 |
+
) -> None:
|
| 102 |
+
self._df: LazyFrameT = df
|
| 103 |
+
self._keys = keys
|
| 104 |
+
self._grouped = self._df._compliant_frame.group_by(
|
| 105 |
+
self._keys, drop_null_keys=drop_null_keys
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def agg(self, *aggs: Expr | Iterable[Expr], **named_aggs: Expr) -> LazyFrameT:
|
| 109 |
+
"""Compute aggregations for each group of a group by operation.
|
| 110 |
+
|
| 111 |
+
Arguments:
|
| 112 |
+
aggs: Aggregations to compute for each group of the group by operation,
|
| 113 |
+
specified as positional arguments.
|
| 114 |
+
named_aggs: Additional aggregations, specified as keyword arguments.
|
| 115 |
+
|
| 116 |
+
Examples:
|
| 117 |
+
Group by one column or by multiple columns and call `agg` to compute
|
| 118 |
+
the grouped sum of another column.
|
| 119 |
+
|
| 120 |
+
>>> import polars as pl
|
| 121 |
+
>>> import narwhals as nw
|
| 122 |
+
>>> from narwhals.typing import IntoFrameT
|
| 123 |
+
>>> lf_native = pl.LazyFrame(
|
| 124 |
+
... {
|
| 125 |
+
... "a": ["a", "b", "a", "b", "c"],
|
| 126 |
+
... "b": [1, 2, 1, 3, 3],
|
| 127 |
+
... "c": [5, 4, 3, 2, 1],
|
| 128 |
+
... }
|
| 129 |
+
... )
|
| 130 |
+
>>> lf = nw.from_native(lf_native)
|
| 131 |
+
>>>
|
| 132 |
+
>>> nw.to_native(lf.group_by("a").agg(nw.col("b").sum()).sort("a")).collect()
|
| 133 |
+
shape: (3, 2)
|
| 134 |
+
┌─────┬─────┐
|
| 135 |
+
│ a ┆ b │
|
| 136 |
+
│ --- ┆ --- │
|
| 137 |
+
│ str ��� i64 │
|
| 138 |
+
╞═════╪═════╡
|
| 139 |
+
│ a ┆ 2 │
|
| 140 |
+
│ b ┆ 5 │
|
| 141 |
+
│ c ┆ 3 │
|
| 142 |
+
└─────┴─────┘
|
| 143 |
+
>>>
|
| 144 |
+
>>> lf.group_by("a", "b").agg(nw.sum("c")).sort("a", "b").collect()
|
| 145 |
+
┌───────────────────┐
|
| 146 |
+
|Narwhals DataFrame |
|
| 147 |
+
|-------------------|
|
| 148 |
+
|shape: (4, 3) |
|
| 149 |
+
|┌─────┬─────┬─────┐|
|
| 150 |
+
|│ a ┆ b ┆ c │|
|
| 151 |
+
|│ --- ┆ --- ┆ --- │|
|
| 152 |
+
|│ str ┆ i64 ┆ i64 │|
|
| 153 |
+
|╞═════╪═════╪═════╡|
|
| 154 |
+
|│ a ┆ 1 ┆ 8 │|
|
| 155 |
+
|│ b ┆ 2 ┆ 4 │|
|
| 156 |
+
|│ b ┆ 3 ┆ 2 │|
|
| 157 |
+
|│ c ┆ 3 ┆ 1 │|
|
| 158 |
+
|└─────┴─────┴─────┘|
|
| 159 |
+
└───────────────────┘
|
| 160 |
+
"""
|
| 161 |
+
compliant_aggs = self._df._flatten_and_extract(*aggs, **named_aggs)
|
| 162 |
+
if not all(is_scalar_like(x) for x in compliant_aggs):
|
| 163 |
+
msg = (
|
| 164 |
+
"Found expression which does not aggregate.\n\n"
|
| 165 |
+
"All expressions passed to GroupBy.agg must aggregate.\n"
|
| 166 |
+
"For example, `df.group_by('a').agg(nw.col('b').sum())` is valid,\n"
|
| 167 |
+
"but `df.group_by('a').agg(nw.col('b'))` is not."
|
| 168 |
+
)
|
| 169 |
+
raise InvalidOperationError(msg)
|
| 170 |
+
return self._df._with_compliant(self._grouped.agg(*compliant_aggs))
|
.venv_haddock/lib/python3.12/site-packages/narwhals/plugins.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from functools import cache
|
| 5 |
+
from typing import TYPE_CHECKING, Any, Protocol, cast
|
| 6 |
+
|
| 7 |
+
from narwhals._compliant import CompliantNamespace
|
| 8 |
+
from narwhals._typing_compat import TypeVar
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from collections.abc import Iterator
|
| 12 |
+
from importlib.metadata import EntryPoints
|
| 13 |
+
|
| 14 |
+
from typing_extensions import LiteralString, TypeAlias
|
| 15 |
+
|
| 16 |
+
from narwhals._compliant.typing import (
|
| 17 |
+
CompliantDataFrameAny,
|
| 18 |
+
CompliantFrameAny,
|
| 19 |
+
CompliantLazyFrameAny,
|
| 20 |
+
CompliantSeriesAny,
|
| 21 |
+
)
|
| 22 |
+
from narwhals.utils import Version
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
__all__ = ["Plugin", "from_native"]
|
| 26 |
+
|
| 27 |
+
CompliantAny: TypeAlias = (
|
| 28 |
+
"CompliantDataFrameAny | CompliantLazyFrameAny | CompliantSeriesAny"
|
| 29 |
+
)
|
| 30 |
+
"""A statically-unknown, Compliant object originating from a plugin."""
|
| 31 |
+
|
| 32 |
+
FrameT = TypeVar(
|
| 33 |
+
"FrameT",
|
| 34 |
+
bound="CompliantFrameAny",
|
| 35 |
+
default="CompliantDataFrameAny | CompliantLazyFrameAny",
|
| 36 |
+
)
|
| 37 |
+
FromNativeR_co = TypeVar(
|
| 38 |
+
"FromNativeR_co", bound=CompliantAny, covariant=True, default=CompliantAny
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@cache
|
| 43 |
+
def _discover_entrypoints() -> EntryPoints:
|
| 44 |
+
from importlib.metadata import entry_points as eps
|
| 45 |
+
|
| 46 |
+
group = "narwhals.plugins"
|
| 47 |
+
if sys.version_info < (3, 10):
|
| 48 |
+
return cast("EntryPoints", eps().get(group, ()))
|
| 49 |
+
return eps(group=group)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class PluginNamespace(CompliantNamespace[FrameT, Any], Protocol[FrameT, FromNativeR_co]):
|
| 53 |
+
def from_native(self, data: Any, /) -> FromNativeR_co: ...
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class Plugin(Protocol[FrameT, FromNativeR_co]):
|
| 57 |
+
@property
|
| 58 |
+
def NATIVE_PACKAGE(self) -> LiteralString: ... # noqa: N802
|
| 59 |
+
|
| 60 |
+
def __narwhals_namespace__(
|
| 61 |
+
self, version: Version
|
| 62 |
+
) -> PluginNamespace[FrameT, FromNativeR_co]: ...
|
| 63 |
+
def is_native(self, native_object: object, /) -> bool: ...
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@cache
|
| 67 |
+
def _might_be(cls: type, type_: str) -> bool: # pragma: no cover
|
| 68 |
+
try:
|
| 69 |
+
return any(type_ in o.__module__.split(".") for o in cls.mro())
|
| 70 |
+
except TypeError:
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _is_native_plugin(native_object: Any, plugin: Plugin) -> bool:
|
| 75 |
+
pkg = plugin.NATIVE_PACKAGE
|
| 76 |
+
return (
|
| 77 |
+
sys.modules.get(pkg) is not None
|
| 78 |
+
and _might_be(type(native_object), pkg) # type: ignore[arg-type]
|
| 79 |
+
and plugin.is_native(native_object)
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _iter_from_native(native_object: Any, version: Version) -> Iterator[CompliantAny]:
|
| 84 |
+
for entry_point in _discover_entrypoints():
|
| 85 |
+
plugin: Plugin = entry_point.load()
|
| 86 |
+
if _is_native_plugin(native_object, plugin):
|
| 87 |
+
compliant_namespace = plugin.__narwhals_namespace__(version=version)
|
| 88 |
+
yield compliant_namespace.from_native(native_object)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def from_native(native_object: Any, version: Version) -> CompliantAny | None:
|
| 92 |
+
"""Attempt to convert `native_object` to a Compliant object, using any available plugin(s).
|
| 93 |
+
|
| 94 |
+
Arguments:
|
| 95 |
+
native_object: Raw object from user.
|
| 96 |
+
version: Narwhals API version.
|
| 97 |
+
|
| 98 |
+
Returns:
|
| 99 |
+
If the following conditions are met
|
| 100 |
+
- at least 1 plugin is installed
|
| 101 |
+
- at least 1 installed plugin supports `type(native_object)`
|
| 102 |
+
|
| 103 |
+
Then for the **first matching plugin**, the result of the call below.
|
| 104 |
+
This *should* be an object accepted by a Narwhals Dataframe, Lazyframe, or Series:
|
| 105 |
+
|
| 106 |
+
plugin: Plugin
|
| 107 |
+
plugin.__narwhals_namespace__(version).from_native(native_object)
|
| 108 |
+
|
| 109 |
+
In all other cases, `None` is returned instead.
|
| 110 |
+
"""
|
| 111 |
+
return next(_iter_from_native(native_object, version), None)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _show_suggestions(native_object_type: type) -> str | None:
|
| 115 |
+
if _might_be(native_object_type, "daft"): # pragma: no cover
|
| 116 |
+
return (
|
| 117 |
+
"Hint: it looks like you passed a `daft.DataFrame` but don't have `narwhals-daft` installed.\n"
|
| 118 |
+
"Please refer to https://github.com/narwhals-dev/narwhals-daft for installation instructions."
|
| 119 |
+
)
|
| 120 |
+
return None
|
.venv_haddock/lib/python3.12/site-packages/narwhals/py.typed
ADDED
|
File without changes
|
.venv_haddock/lib/python3.12/site-packages/narwhals/schema.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Schema.
|
| 2 |
+
|
| 3 |
+
Adapted from Polars implementation at:
|
| 4 |
+
https://github.com/pola-rs/polars/blob/main/py-polars/polars/schema.py.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from collections import OrderedDict
|
| 10 |
+
from collections.abc import Mapping
|
| 11 |
+
from functools import partial
|
| 12 |
+
from typing import TYPE_CHECKING, cast
|
| 13 |
+
|
| 14 |
+
from narwhals._utils import Implementation, Version, qualified_type_name, zip_strict
|
| 15 |
+
from narwhals.dependencies import (
|
| 16 |
+
get_cudf,
|
| 17 |
+
is_cudf_dtype,
|
| 18 |
+
is_pandas_like_dtype,
|
| 19 |
+
is_polars_data_type,
|
| 20 |
+
is_polars_schema,
|
| 21 |
+
is_pyarrow_data_type,
|
| 22 |
+
is_pyarrow_schema,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from collections.abc import Iterable
|
| 27 |
+
from typing import Any, ClassVar
|
| 28 |
+
|
| 29 |
+
import polars as pl
|
| 30 |
+
import pyarrow as pa
|
| 31 |
+
from typing_extensions import Self
|
| 32 |
+
|
| 33 |
+
from narwhals.dtypes import DType
|
| 34 |
+
from narwhals.typing import (
|
| 35 |
+
DTypeBackend,
|
| 36 |
+
IntoArrowSchema,
|
| 37 |
+
IntoPandasSchema,
|
| 38 |
+
IntoPolarsSchema,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
__all__ = ["Schema"]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class Schema(OrderedDict[str, "DType"]):
|
| 46 |
+
"""Ordered mapping of column names to their data type.
|
| 47 |
+
|
| 48 |
+
Arguments:
|
| 49 |
+
schema: The schema definition given by column names and their associated
|
| 50 |
+
*instantiated* Narwhals data type. Accepts a mapping or an iterable of tuples.
|
| 51 |
+
|
| 52 |
+
Examples:
|
| 53 |
+
Define a schema by passing *instantiated* data types.
|
| 54 |
+
|
| 55 |
+
>>> import narwhals as nw
|
| 56 |
+
>>> schema = nw.Schema({"foo": nw.Int8(), "bar": nw.String()})
|
| 57 |
+
>>> schema
|
| 58 |
+
Schema({'foo': Int8, 'bar': String})
|
| 59 |
+
|
| 60 |
+
Access the data type associated with a specific column name.
|
| 61 |
+
|
| 62 |
+
>>> schema["foo"]
|
| 63 |
+
Int8
|
| 64 |
+
|
| 65 |
+
Access various schema properties using the `names`, `dtypes`, and `len` methods.
|
| 66 |
+
|
| 67 |
+
>>> schema.names()
|
| 68 |
+
['foo', 'bar']
|
| 69 |
+
>>> schema.dtypes()
|
| 70 |
+
[Int8, String]
|
| 71 |
+
>>> schema.len()
|
| 72 |
+
2
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
_version: ClassVar[Version] = Version.MAIN
|
| 76 |
+
|
| 77 |
+
def __init__(
|
| 78 |
+
self, schema: Mapping[str, DType] | Iterable[tuple[str, DType]] | None = None
|
| 79 |
+
) -> None:
|
| 80 |
+
schema = schema or {}
|
| 81 |
+
super().__init__(schema)
|
| 82 |
+
|
| 83 |
+
def names(self) -> list[str]:
|
| 84 |
+
"""Get the column names of the schema."""
|
| 85 |
+
return list(self.keys())
|
| 86 |
+
|
| 87 |
+
def dtypes(self) -> list[DType]:
|
| 88 |
+
"""Get the data types of the schema."""
|
| 89 |
+
return list(self.values())
|
| 90 |
+
|
| 91 |
+
def len(self) -> int:
|
| 92 |
+
"""Get the number of columns in the schema."""
|
| 93 |
+
return len(self)
|
| 94 |
+
|
| 95 |
+
@classmethod
|
| 96 |
+
def from_arrow(cls, schema: IntoArrowSchema, /) -> Self:
|
| 97 |
+
"""Construct a Schema from a pyarrow Schema.
|
| 98 |
+
|
| 99 |
+
Arguments:
|
| 100 |
+
schema: A pyarrow Schema or mapping of column names to pyarrow data types.
|
| 101 |
+
|
| 102 |
+
Examples:
|
| 103 |
+
>>> import pyarrow as pa
|
| 104 |
+
>>> import narwhals as nw
|
| 105 |
+
>>>
|
| 106 |
+
>>> mapping = {
|
| 107 |
+
... "a": pa.timestamp("us", "UTC"),
|
| 108 |
+
... "b": pa.date32(),
|
| 109 |
+
... "c": pa.string(),
|
| 110 |
+
... "d": pa.uint8(),
|
| 111 |
+
... }
|
| 112 |
+
>>> native = pa.schema(mapping)
|
| 113 |
+
>>>
|
| 114 |
+
>>> nw.Schema.from_arrow(native)
|
| 115 |
+
Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8})
|
| 116 |
+
|
| 117 |
+
>>> nw.Schema.from_arrow(mapping) == nw.Schema.from_arrow(native)
|
| 118 |
+
True
|
| 119 |
+
"""
|
| 120 |
+
if isinstance(schema, Mapping):
|
| 121 |
+
if not schema:
|
| 122 |
+
return cls()
|
| 123 |
+
import pyarrow as pa # ignore-banned-import
|
| 124 |
+
|
| 125 |
+
schema = pa.schema(schema)
|
| 126 |
+
from narwhals._arrow.utils import native_to_narwhals_dtype
|
| 127 |
+
|
| 128 |
+
return cls(
|
| 129 |
+
(field.name, native_to_narwhals_dtype(field.type, cls._version))
|
| 130 |
+
for field in schema
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
@classmethod
|
| 134 |
+
def from_pandas_like(cls, schema: IntoPandasSchema, /) -> Self:
|
| 135 |
+
"""Construct a Schema from a pandas-like schema representation.
|
| 136 |
+
|
| 137 |
+
Arguments:
|
| 138 |
+
schema: A mapping of column names to pandas-like data types.
|
| 139 |
+
|
| 140 |
+
Examples:
|
| 141 |
+
>>> import numpy as np
|
| 142 |
+
>>> import pandas as pd
|
| 143 |
+
>>> import pyarrow as pa
|
| 144 |
+
>>> import narwhals as nw
|
| 145 |
+
>>>
|
| 146 |
+
>>> data = {"a": [1], "b": ["a"], "c": [False], "d": [9.2]}
|
| 147 |
+
>>> native = pd.DataFrame(data).convert_dtypes().dtypes.to_dict()
|
| 148 |
+
>>>
|
| 149 |
+
>>> nw.Schema.from_pandas_like(native)
|
| 150 |
+
Schema({'a': Int64, 'b': String, 'c': Boolean, 'd': Float64})
|
| 151 |
+
>>>
|
| 152 |
+
>>> mapping = {
|
| 153 |
+
... "a": pd.DatetimeTZDtype("us", "UTC"),
|
| 154 |
+
... "b": pd.ArrowDtype(pa.date32()),
|
| 155 |
+
... "c": pd.StringDtype("python"),
|
| 156 |
+
... "d": np.dtype("uint8"),
|
| 157 |
+
... }
|
| 158 |
+
>>>
|
| 159 |
+
>>> nw.Schema.from_pandas_like(mapping)
|
| 160 |
+
Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8})
|
| 161 |
+
"""
|
| 162 |
+
if not schema:
|
| 163 |
+
return cls()
|
| 164 |
+
impl = (
|
| 165 |
+
Implementation.CUDF
|
| 166 |
+
if get_cudf() and any(is_cudf_dtype(dtype) for dtype in schema.values())
|
| 167 |
+
else Implementation.PANDAS
|
| 168 |
+
)
|
| 169 |
+
return cls._from_pandas_like(schema, impl)
|
| 170 |
+
|
| 171 |
+
@classmethod
|
| 172 |
+
def from_native(
|
| 173 |
+
cls, schema: IntoArrowSchema | IntoPolarsSchema | IntoPandasSchema, /
|
| 174 |
+
) -> Self:
|
| 175 |
+
"""Construct a Schema from a native schema representation.
|
| 176 |
+
|
| 177 |
+
Arguments:
|
| 178 |
+
schema: A native schema object, or mapping of column names to
|
| 179 |
+
*instantiated* native data types.
|
| 180 |
+
|
| 181 |
+
Examples:
|
| 182 |
+
>>> import datetime as dt
|
| 183 |
+
>>> import pyarrow as pa
|
| 184 |
+
>>> import narwhals as nw
|
| 185 |
+
>>>
|
| 186 |
+
>>> data = {"a": [1], "b": ["a"], "c": [dt.time(1, 2, 3)], "d": [[2]]}
|
| 187 |
+
>>> native = pa.table(data).schema
|
| 188 |
+
>>>
|
| 189 |
+
>>> nw.Schema.from_native(native)
|
| 190 |
+
Schema({'a': Int64, 'b': String, 'c': Time, 'd': List(Int64)})
|
| 191 |
+
"""
|
| 192 |
+
if is_pyarrow_schema(schema):
|
| 193 |
+
return cls.from_arrow(schema)
|
| 194 |
+
if is_polars_schema(schema):
|
| 195 |
+
return cls.from_polars(schema)
|
| 196 |
+
if isinstance(schema, Mapping):
|
| 197 |
+
return cls._from_native_mapping(schema) if schema else cls()
|
| 198 |
+
msg = (
|
| 199 |
+
f"Expected an arrow, polars, or pandas schema, but got "
|
| 200 |
+
f"{qualified_type_name(schema)!r}\n\n{schema!r}"
|
| 201 |
+
)
|
| 202 |
+
raise TypeError(msg)
|
| 203 |
+
|
| 204 |
+
@classmethod
|
| 205 |
+
def from_polars(cls, schema: IntoPolarsSchema, /) -> Self:
|
| 206 |
+
"""Construct a Schema from a polars Schema.
|
| 207 |
+
|
| 208 |
+
Arguments:
|
| 209 |
+
schema: A polars Schema or mapping of column names to *instantiated*
|
| 210 |
+
polars data types.
|
| 211 |
+
|
| 212 |
+
Examples:
|
| 213 |
+
>>> import polars as pl
|
| 214 |
+
>>> import narwhals as nw
|
| 215 |
+
>>>
|
| 216 |
+
>>> mapping = {
|
| 217 |
+
... "a": pl.Datetime(time_zone="UTC"),
|
| 218 |
+
... "b": pl.Date(),
|
| 219 |
+
... "c": pl.String(),
|
| 220 |
+
... "d": pl.UInt8(),
|
| 221 |
+
... }
|
| 222 |
+
>>> native = pl.Schema(mapping)
|
| 223 |
+
>>>
|
| 224 |
+
>>> nw.Schema.from_polars(native)
|
| 225 |
+
Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8})
|
| 226 |
+
|
| 227 |
+
>>> nw.Schema.from_polars(mapping) == nw.Schema.from_polars(native)
|
| 228 |
+
True
|
| 229 |
+
"""
|
| 230 |
+
if not schema:
|
| 231 |
+
return cls()
|
| 232 |
+
from narwhals._polars.utils import native_to_narwhals_dtype
|
| 233 |
+
|
| 234 |
+
return cls(
|
| 235 |
+
(name, native_to_narwhals_dtype(dtype, cls._version))
|
| 236 |
+
for name, dtype in schema.items()
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
def to_arrow(self) -> pa.Schema:
|
| 240 |
+
"""Convert Schema to a pyarrow Schema.
|
| 241 |
+
|
| 242 |
+
Examples:
|
| 243 |
+
>>> import narwhals as nw
|
| 244 |
+
>>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
|
| 245 |
+
>>> schema.to_arrow()
|
| 246 |
+
a: int64
|
| 247 |
+
b: timestamp[ns]
|
| 248 |
+
"""
|
| 249 |
+
import pyarrow as pa # ignore-banned-import
|
| 250 |
+
|
| 251 |
+
from narwhals._arrow.utils import narwhals_to_native_dtype
|
| 252 |
+
|
| 253 |
+
return pa.schema(
|
| 254 |
+
(name, narwhals_to_native_dtype(dtype, self._version))
|
| 255 |
+
for name, dtype in self.items()
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
def to_pandas(
|
| 259 |
+
self, dtype_backend: DTypeBackend | Iterable[DTypeBackend] = None
|
| 260 |
+
) -> dict[str, Any]:
|
| 261 |
+
"""Convert Schema to an ordered mapping of column names to their pandas data type.
|
| 262 |
+
|
| 263 |
+
Arguments:
|
| 264 |
+
dtype_backend: Backend(s) used for the native types. When providing more than
|
| 265 |
+
one, the length of the iterable must be equal to the length of the schema.
|
| 266 |
+
|
| 267 |
+
Examples:
|
| 268 |
+
>>> import narwhals as nw
|
| 269 |
+
>>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
|
| 270 |
+
>>> schema.to_pandas()
|
| 271 |
+
{'a': 'int64', 'b': 'datetime64[ns]'}
|
| 272 |
+
|
| 273 |
+
>>> schema.to_pandas("pyarrow")
|
| 274 |
+
{'a': 'Int64[pyarrow]', 'b': 'timestamp[ns][pyarrow]'}
|
| 275 |
+
"""
|
| 276 |
+
from narwhals._pandas_like.utils import narwhals_to_native_dtype
|
| 277 |
+
|
| 278 |
+
to_native_dtype = partial(
|
| 279 |
+
narwhals_to_native_dtype,
|
| 280 |
+
implementation=Implementation.PANDAS,
|
| 281 |
+
version=self._version,
|
| 282 |
+
)
|
| 283 |
+
if dtype_backend is None or isinstance(dtype_backend, str):
|
| 284 |
+
return {
|
| 285 |
+
name: to_native_dtype(dtype=dtype, dtype_backend=dtype_backend)
|
| 286 |
+
for name, dtype in self.items()
|
| 287 |
+
}
|
| 288 |
+
backends = tuple(dtype_backend)
|
| 289 |
+
if len(backends) != len(self):
|
| 290 |
+
from itertools import chain, islice, repeat
|
| 291 |
+
|
| 292 |
+
n_user, n_actual = len(backends), len(self)
|
| 293 |
+
suggestion = tuple(
|
| 294 |
+
islice(chain.from_iterable(islice(repeat(backends), n_actual)), n_actual)
|
| 295 |
+
)
|
| 296 |
+
msg = (
|
| 297 |
+
f"Provided {n_user!r} `dtype_backend`(s), but schema contains {n_actual!r} field(s).\n"
|
| 298 |
+
"Hint: instead of\n"
|
| 299 |
+
f" schema.to_pandas({backends})\n"
|
| 300 |
+
"you may want to use\n"
|
| 301 |
+
f" schema.to_pandas({backends[0]})\n"
|
| 302 |
+
f"or\n"
|
| 303 |
+
f" schema.to_pandas({suggestion})"
|
| 304 |
+
)
|
| 305 |
+
raise ValueError(msg)
|
| 306 |
+
return {
|
| 307 |
+
name: to_native_dtype(dtype=dtype, dtype_backend=backend)
|
| 308 |
+
for name, dtype, backend in zip_strict(self.keys(), self.values(), backends)
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
def to_polars(self) -> pl.Schema:
|
| 312 |
+
"""Convert Schema to a polars Schema.
|
| 313 |
+
|
| 314 |
+
Examples:
|
| 315 |
+
>>> import narwhals as nw
|
| 316 |
+
>>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
|
| 317 |
+
>>> schema.to_polars()
|
| 318 |
+
Schema({'a': Int64, 'b': Datetime(time_unit='ns', time_zone=None)})
|
| 319 |
+
"""
|
| 320 |
+
import polars as pl # ignore-banned-import
|
| 321 |
+
|
| 322 |
+
from narwhals._polars.utils import narwhals_to_native_dtype
|
| 323 |
+
|
| 324 |
+
pl_version = Implementation.POLARS._backend_version()
|
| 325 |
+
schema = (
|
| 326 |
+
(name, narwhals_to_native_dtype(dtype, self._version))
|
| 327 |
+
for name, dtype in self.items()
|
| 328 |
+
)
|
| 329 |
+
return (
|
| 330 |
+
pl.Schema(schema)
|
| 331 |
+
if pl_version >= (1, 0, 0)
|
| 332 |
+
else cast("pl.Schema", dict(schema))
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@classmethod
|
| 336 |
+
def _from_native_mapping(
|
| 337 |
+
cls,
|
| 338 |
+
native: Mapping[str, pa.DataType] | Mapping[str, pl.DataType] | IntoPandasSchema,
|
| 339 |
+
/,
|
| 340 |
+
) -> Self:
|
| 341 |
+
first_item = next(iter(native.items()))
|
| 342 |
+
first_key, first_dtype = first_item
|
| 343 |
+
if is_polars_data_type(first_dtype):
|
| 344 |
+
return cls.from_polars(cast("IntoPolarsSchema", native))
|
| 345 |
+
if is_pandas_like_dtype(first_dtype):
|
| 346 |
+
return cls.from_pandas_like(cast("IntoPandasSchema", native))
|
| 347 |
+
if is_pyarrow_data_type(first_dtype):
|
| 348 |
+
return cls.from_arrow(cast("IntoArrowSchema", native))
|
| 349 |
+
msg = (
|
| 350 |
+
f"Expected an arrow, polars, or pandas dtype, but found "
|
| 351 |
+
f"`{first_key}: {qualified_type_name(first_dtype)}`\n\n{native!r}"
|
| 352 |
+
)
|
| 353 |
+
raise TypeError(msg)
|
| 354 |
+
|
| 355 |
+
@classmethod
|
| 356 |
+
def _from_pandas_like(
|
| 357 |
+
cls, schema: IntoPandasSchema, implementation: Implementation, /
|
| 358 |
+
) -> Self:
|
| 359 |
+
from narwhals._pandas_like.utils import native_to_narwhals_dtype
|
| 360 |
+
|
| 361 |
+
impl = implementation
|
| 362 |
+
return cls(
|
| 363 |
+
(name, native_to_narwhals_dtype(dtype, cls._version, impl, allow_object=True))
|
| 364 |
+
for name, dtype in schema.items()
|
| 365 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/selectors.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any, NoReturn
|
| 4 |
+
|
| 5 |
+
from narwhals._expression_parsing import ExprKind, ExprNode
|
| 6 |
+
from narwhals._utils import flatten
|
| 7 |
+
from narwhals.expr import Expr
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from collections.abc import Iterable
|
| 11 |
+
from datetime import timezone
|
| 12 |
+
|
| 13 |
+
from narwhals.dtypes import DType
|
| 14 |
+
from narwhals.typing import TimeUnit
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Selector(Expr):
|
| 18 |
+
def _to_expr(self) -> Expr:
|
| 19 |
+
return Expr(*self._nodes)
|
| 20 |
+
|
| 21 |
+
def __add__(self, other: Any) -> Expr: # type: ignore[override]
|
| 22 |
+
if isinstance(other, Selector):
|
| 23 |
+
msg = "unsupported operand type(s) for op: ('Selector' + 'Selector')"
|
| 24 |
+
raise TypeError(msg)
|
| 25 |
+
return self._to_expr()._append_node(
|
| 26 |
+
ExprNode(ExprKind.ELEMENTWISE, "__add__", exprs=(other,), str_as_lit=True)
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
def __or__(self, other: Any) -> Expr: # type: ignore[override]
|
| 30 |
+
if isinstance(other, Selector):
|
| 31 |
+
return self._append_node(
|
| 32 |
+
ExprNode(
|
| 33 |
+
ExprKind.ELEMENTWISE,
|
| 34 |
+
"__or__",
|
| 35 |
+
exprs=(other,),
|
| 36 |
+
str_as_lit=True,
|
| 37 |
+
allow_multi_output=True,
|
| 38 |
+
)
|
| 39 |
+
)
|
| 40 |
+
return self._to_expr()._append_node(
|
| 41 |
+
ExprNode(ExprKind.ELEMENTWISE, "__or__", exprs=(other,), str_as_lit=True)
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
def __and__(self, other: Any) -> Expr: # type: ignore[override]
|
| 45 |
+
if isinstance(other, Selector):
|
| 46 |
+
return self._append_node(
|
| 47 |
+
ExprNode(
|
| 48 |
+
ExprKind.ELEMENTWISE,
|
| 49 |
+
"__and__",
|
| 50 |
+
exprs=(other,),
|
| 51 |
+
str_as_lit=True,
|
| 52 |
+
allow_multi_output=True,
|
| 53 |
+
)
|
| 54 |
+
)
|
| 55 |
+
return self._to_expr()._append_node(
|
| 56 |
+
ExprNode(ExprKind.ELEMENTWISE, "__and__", exprs=(other,), str_as_lit=True)
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def __rsub__(self, other: Any) -> NoReturn:
|
| 60 |
+
raise NotImplementedError
|
| 61 |
+
|
| 62 |
+
def __rand__(self, other: Any) -> NoReturn:
|
| 63 |
+
raise NotImplementedError
|
| 64 |
+
|
| 65 |
+
def __ror__(self, other: Any) -> NoReturn:
|
| 66 |
+
raise NotImplementedError
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def by_dtype(*dtypes: DType | type[DType] | Iterable[DType | type[DType]]) -> Selector:
|
| 70 |
+
"""Select columns based on their dtype.
|
| 71 |
+
|
| 72 |
+
Arguments:
|
| 73 |
+
dtypes: one or data types to select
|
| 74 |
+
|
| 75 |
+
Examples:
|
| 76 |
+
>>> import pyarrow as pa
|
| 77 |
+
>>> import narwhals as nw
|
| 78 |
+
>>> import narwhals.selectors as ncs
|
| 79 |
+
>>> df_native = pa.table({"a": [1, 2], "b": ["x", "y"], "c": [4.1, 2.3]})
|
| 80 |
+
>>> df = nw.from_native(df_native)
|
| 81 |
+
|
| 82 |
+
Let's select int64 and float64 dtypes and multiply each value by 2:
|
| 83 |
+
|
| 84 |
+
>>> df.select(ncs.by_dtype(nw.Int64, nw.Float64) * 2).to_native()
|
| 85 |
+
pyarrow.Table
|
| 86 |
+
a: int64
|
| 87 |
+
c: double
|
| 88 |
+
----
|
| 89 |
+
a: [[2,4]]
|
| 90 |
+
c: [[8.2,4.6]]
|
| 91 |
+
"""
|
| 92 |
+
flattened = flatten(dtypes)
|
| 93 |
+
return Selector(ExprNode(ExprKind.SELECTOR, "selectors.by_dtype", dtypes=flattened))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def matches(pattern: str) -> Selector:
|
| 97 |
+
"""Select all columns that match the given regex pattern.
|
| 98 |
+
|
| 99 |
+
Arguments:
|
| 100 |
+
pattern: A valid regular expression pattern.
|
| 101 |
+
|
| 102 |
+
Examples:
|
| 103 |
+
>>> import pandas as pd
|
| 104 |
+
>>> import narwhals as nw
|
| 105 |
+
>>> import narwhals.selectors as ncs
|
| 106 |
+
>>> df_native = pd.DataFrame(
|
| 107 |
+
... {"bar": [123, 456], "baz": [2.0, 5.5], "zap": [0, 1]}
|
| 108 |
+
... )
|
| 109 |
+
>>> df = nw.from_native(df_native)
|
| 110 |
+
|
| 111 |
+
Let's select column names containing an 'a', preceded by a character that is not 'z':
|
| 112 |
+
|
| 113 |
+
>>> df.select(ncs.matches("[^z]a")).to_native()
|
| 114 |
+
bar baz
|
| 115 |
+
0 123 2.0
|
| 116 |
+
1 456 5.5
|
| 117 |
+
"""
|
| 118 |
+
return Selector(ExprNode(ExprKind.SELECTOR, "selectors.matches", pattern=pattern))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def numeric() -> Selector:
|
| 122 |
+
"""Select numeric columns.
|
| 123 |
+
|
| 124 |
+
Examples:
|
| 125 |
+
>>> import polars as pl
|
| 126 |
+
>>> import narwhals as nw
|
| 127 |
+
>>> import narwhals.selectors as ncs
|
| 128 |
+
>>> df_native = pl.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [4.1, 2.3]})
|
| 129 |
+
>>> df = nw.from_native(df_native)
|
| 130 |
+
|
| 131 |
+
Let's select numeric dtypes and multiply each value by 2:
|
| 132 |
+
|
| 133 |
+
>>> df.select(ncs.numeric() * 2).to_native()
|
| 134 |
+
shape: (2, 2)
|
| 135 |
+
┌─────┬─────┐
|
| 136 |
+
│ a ┆ c │
|
| 137 |
+
│ --- ┆ --- │
|
| 138 |
+
│ i64 ┆ f64 │
|
| 139 |
+
╞═════╪═════╡
|
| 140 |
+
│ 2 ┆ 8.2 │
|
| 141 |
+
│ 4 ┆ 4.6 │
|
| 142 |
+
└─────┴─────┘
|
| 143 |
+
"""
|
| 144 |
+
return Selector(ExprNode(ExprKind.SELECTOR, "selectors.numeric"))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def boolean() -> Selector:
|
| 148 |
+
"""Select boolean columns.
|
| 149 |
+
|
| 150 |
+
Examples:
|
| 151 |
+
>>> import polars as pl
|
| 152 |
+
>>> import narwhals as nw
|
| 153 |
+
>>> import narwhals.selectors as ncs
|
| 154 |
+
>>> df_native = pl.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [False, True]})
|
| 155 |
+
>>> df = nw.from_native(df_native)
|
| 156 |
+
|
| 157 |
+
Let's select boolean dtypes:
|
| 158 |
+
|
| 159 |
+
>>> df.select(ncs.boolean())
|
| 160 |
+
┌──────────────────┐
|
| 161 |
+
|Narwhals DataFrame|
|
| 162 |
+
|------------------|
|
| 163 |
+
| shape: (2, 1) |
|
| 164 |
+
| ┌───────┐ |
|
| 165 |
+
| │ c │ |
|
| 166 |
+
| │ --- │ |
|
| 167 |
+
| │ bool │ |
|
| 168 |
+
| ╞═══════╡ |
|
| 169 |
+
| │ false │ |
|
| 170 |
+
| │ true │ |
|
| 171 |
+
| └───────┘ |
|
| 172 |
+
└──────────────────┘
|
| 173 |
+
"""
|
| 174 |
+
return Selector(ExprNode(ExprKind.SELECTOR, "selectors.boolean"))
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def string() -> Selector:
|
| 178 |
+
"""Select string columns.
|
| 179 |
+
|
| 180 |
+
Examples:
|
| 181 |
+
>>> import polars as pl
|
| 182 |
+
>>> import narwhals as nw
|
| 183 |
+
>>> import narwhals.selectors as ncs
|
| 184 |
+
>>> df_native = pl.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [False, True]})
|
| 185 |
+
>>> df = nw.from_native(df_native)
|
| 186 |
+
|
| 187 |
+
Let's select string dtypes:
|
| 188 |
+
|
| 189 |
+
>>> df.select(ncs.string()).to_native()
|
| 190 |
+
shape: (2, 1)
|
| 191 |
+
┌─────┐
|
| 192 |
+
│ b │
|
| 193 |
+
│ --- │
|
| 194 |
+
│ str │
|
| 195 |
+
╞═════╡
|
| 196 |
+
│ x │
|
| 197 |
+
│ y │
|
| 198 |
+
└─────┘
|
| 199 |
+
"""
|
| 200 |
+
return Selector(ExprNode(ExprKind.SELECTOR, "selectors.string"))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def categorical() -> Selector:
|
| 204 |
+
"""Select categorical columns.
|
| 205 |
+
|
| 206 |
+
Examples:
|
| 207 |
+
>>> import polars as pl
|
| 208 |
+
>>> import narwhals as nw
|
| 209 |
+
>>> import narwhals.selectors as ncs
|
| 210 |
+
>>> df_native = pl.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [False, True]})
|
| 211 |
+
|
| 212 |
+
Let's convert column "b" to categorical, and then select categorical dtypes:
|
| 213 |
+
|
| 214 |
+
>>> df = nw.from_native(df_native).with_columns(
|
| 215 |
+
... b=nw.col("b").cast(nw.Categorical())
|
| 216 |
+
... )
|
| 217 |
+
>>> df.select(ncs.categorical()).to_native()
|
| 218 |
+
shape: (2, 1)
|
| 219 |
+
┌─────┐
|
| 220 |
+
│ b │
|
| 221 |
+
│ --- │
|
| 222 |
+
│ cat │
|
| 223 |
+
╞═════╡
|
| 224 |
+
│ x │
|
| 225 |
+
│ y │
|
| 226 |
+
└─────┘
|
| 227 |
+
"""
|
| 228 |
+
return Selector(ExprNode(ExprKind.SELECTOR, "selectors.categorical"))
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def all() -> Selector:
|
| 232 |
+
"""Select all columns.
|
| 233 |
+
|
| 234 |
+
Examples:
|
| 235 |
+
>>> import pandas as pd
|
| 236 |
+
>>> import narwhals as nw
|
| 237 |
+
>>> import narwhals.selectors as ncs
|
| 238 |
+
>>> df_native = pd.DataFrame({"a": [1, 2], "b": ["x", "y"], "c": [False, True]})
|
| 239 |
+
>>> df = nw.from_native(df_native)
|
| 240 |
+
|
| 241 |
+
Let's select all dtypes:
|
| 242 |
+
|
| 243 |
+
>>> df.select(ncs.all()).to_native()
|
| 244 |
+
a b c
|
| 245 |
+
0 1 x False
|
| 246 |
+
1 2 y True
|
| 247 |
+
"""
|
| 248 |
+
return Selector(ExprNode(ExprKind.SELECTOR, "selectors.all"))
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def datetime(
|
| 252 |
+
time_unit: TimeUnit | Iterable[TimeUnit] | None = None,
|
| 253 |
+
time_zone: str | timezone | Iterable[str | timezone | None] | None = ("*", None),
|
| 254 |
+
) -> Selector:
|
| 255 |
+
"""Select all datetime columns, optionally filtering by time unit/zone.
|
| 256 |
+
|
| 257 |
+
Arguments:
|
| 258 |
+
time_unit: One (or more) of the allowed timeunit precision strings, "ms", "us",
|
| 259 |
+
"ns" and "s". Omit to select columns with any valid timeunit.
|
| 260 |
+
time_zone: Specify which timezone(s) to select
|
| 261 |
+
|
| 262 |
+
* One or more timezone strings, as defined in zoneinfo (to see valid options
|
| 263 |
+
run `import zoneinfo; zoneinfo.available_timezones()` for a full list).
|
| 264 |
+
* Set `None` to select Datetime columns that do not have a timezone.
|
| 265 |
+
* Set `"*"` to select Datetime columns that have *any* timezone.
|
| 266 |
+
|
| 267 |
+
Examples:
|
| 268 |
+
>>> from datetime import datetime, timezone
|
| 269 |
+
>>> import pyarrow as pa
|
| 270 |
+
>>> import narwhals as nw
|
| 271 |
+
>>> import narwhals.selectors as ncs
|
| 272 |
+
>>>
|
| 273 |
+
>>> utc_tz = timezone.utc
|
| 274 |
+
>>> data = {
|
| 275 |
+
... "tstamp_utc": [
|
| 276 |
+
... datetime(2023, 4, 10, 12, 14, 16, 999000, tzinfo=utc_tz),
|
| 277 |
+
... datetime(2025, 8, 25, 14, 18, 22, 666000, tzinfo=utc_tz),
|
| 278 |
+
... ],
|
| 279 |
+
... "tstamp": [
|
| 280 |
+
... datetime(2000, 11, 20, 18, 12, 16, 600000),
|
| 281 |
+
... datetime(2020, 10, 30, 10, 20, 25, 123000),
|
| 282 |
+
... ],
|
| 283 |
+
... "numeric": [3.14, 6.28],
|
| 284 |
+
... }
|
| 285 |
+
>>> df_native = pa.table(data)
|
| 286 |
+
>>> df_nw = nw.from_native(df_native)
|
| 287 |
+
>>> df_nw.select(ncs.datetime()).to_native()
|
| 288 |
+
pyarrow.Table
|
| 289 |
+
tstamp_utc: timestamp[us, tz=UTC]
|
| 290 |
+
tstamp: timestamp[us]
|
| 291 |
+
----
|
| 292 |
+
tstamp_utc: [[2023-04-10 12:14:16.999000Z,2025-08-25 14:18:22.666000Z]]
|
| 293 |
+
tstamp: [[2000-11-20 18:12:16.600000,2020-10-30 10:20:25.123000]]
|
| 294 |
+
|
| 295 |
+
Select only datetime columns that have any time_zone specification:
|
| 296 |
+
|
| 297 |
+
>>> df_nw.select(ncs.datetime(time_zone="*")).to_native()
|
| 298 |
+
pyarrow.Table
|
| 299 |
+
tstamp_utc: timestamp[us, tz=UTC]
|
| 300 |
+
----
|
| 301 |
+
tstamp_utc: [[2023-04-10 12:14:16.999000Z,2025-08-25 14:18:22.666000Z]]
|
| 302 |
+
"""
|
| 303 |
+
return Selector(
|
| 304 |
+
ExprNode(
|
| 305 |
+
ExprKind.SELECTOR,
|
| 306 |
+
"selectors.datetime",
|
| 307 |
+
time_unit=time_unit,
|
| 308 |
+
time_zone=time_zone,
|
| 309 |
+
)
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
__all__ = [
|
| 314 |
+
"all",
|
| 315 |
+
"boolean",
|
| 316 |
+
"by_dtype",
|
| 317 |
+
"categorical",
|
| 318 |
+
"datetime",
|
| 319 |
+
"matches",
|
| 320 |
+
"numeric",
|
| 321 |
+
"string",
|
| 322 |
+
]
|
.venv_haddock/lib/python3.12/site-packages/narwhals/series.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/series_cat.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Generic
|
| 4 |
+
|
| 5 |
+
from narwhals.typing import SeriesT
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SeriesCatNamespace(Generic[SeriesT]):
|
| 9 |
+
def __init__(self, series: SeriesT) -> None:
|
| 10 |
+
self._narwhals_series = series
|
| 11 |
+
|
| 12 |
+
def get_categories(self) -> SeriesT:
|
| 13 |
+
"""Get unique categories from column.
|
| 14 |
+
|
| 15 |
+
Examples:
|
| 16 |
+
>>> import pandas as pd
|
| 17 |
+
>>> import narwhals as nw
|
| 18 |
+
>>> s_native = pd.Series(["apple", "mango", "mango"], dtype="category")
|
| 19 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 20 |
+
>>> s.cat.get_categories().to_native()
|
| 21 |
+
0 apple
|
| 22 |
+
1 mango
|
| 23 |
+
dtype: str
|
| 24 |
+
"""
|
| 25 |
+
return self._narwhals_series._with_compliant(
|
| 26 |
+
self._narwhals_series._compliant_series.cat.get_categories()
|
| 27 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/series_dt.py
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Generic
|
| 4 |
+
|
| 5 |
+
from narwhals.typing import SeriesT
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from narwhals.typing import TimeUnit
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SeriesDateTimeNamespace(Generic[SeriesT]):
|
| 12 |
+
def __init__(self, series: SeriesT) -> None:
|
| 13 |
+
self._narwhals_series = series
|
| 14 |
+
|
| 15 |
+
def date(self) -> SeriesT:
|
| 16 |
+
"""Get the date in a datetime series.
|
| 17 |
+
|
| 18 |
+
Raises:
|
| 19 |
+
NotImplementedError: If pandas default backend is being used.
|
| 20 |
+
|
| 21 |
+
Examples:
|
| 22 |
+
>>> from datetime import datetime
|
| 23 |
+
>>> import pandas as pd
|
| 24 |
+
>>> import narwhals as nw
|
| 25 |
+
>>> s_native = pd.Series(
|
| 26 |
+
... [datetime(2012, 1, 7, 10, 20), datetime(2023, 3, 10, 11, 32)]
|
| 27 |
+
... ).convert_dtypes(dtype_backend="pyarrow")
|
| 28 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 29 |
+
>>> s.dt.date().to_native()
|
| 30 |
+
0 2012-01-07
|
| 31 |
+
1 2023-03-10
|
| 32 |
+
dtype: date32[day][pyarrow]
|
| 33 |
+
"""
|
| 34 |
+
return self._narwhals_series._with_compliant(
|
| 35 |
+
self._narwhals_series._compliant_series.dt.date()
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
def year(self) -> SeriesT:
|
| 39 |
+
"""Get the year in a datetime series.
|
| 40 |
+
|
| 41 |
+
Examples:
|
| 42 |
+
>>> from datetime import datetime
|
| 43 |
+
>>> import polars as pl
|
| 44 |
+
>>> import narwhals as nw
|
| 45 |
+
>>> s_native = pl.Series([datetime(2012, 1, 7), datetime(2023, 3, 10)])
|
| 46 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 47 |
+
>>> s.dt.year().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 48 |
+
shape: (2,)
|
| 49 |
+
Series: '' [i32]
|
| 50 |
+
[
|
| 51 |
+
2012
|
| 52 |
+
2023
|
| 53 |
+
]
|
| 54 |
+
"""
|
| 55 |
+
return self._narwhals_series._with_compliant(
|
| 56 |
+
self._narwhals_series._compliant_series.dt.year()
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def month(self) -> SeriesT:
|
| 60 |
+
"""Gets the month in a datetime series.
|
| 61 |
+
|
| 62 |
+
Examples:
|
| 63 |
+
>>> from datetime import datetime
|
| 64 |
+
>>> import polars as pl
|
| 65 |
+
>>> import narwhals as nw
|
| 66 |
+
>>> s_native = pl.Series([datetime(2012, 1, 7), datetime(2023, 3, 10)])
|
| 67 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 68 |
+
>>> s.dt.month().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 69 |
+
shape: (2,)
|
| 70 |
+
Series: '' [i8]
|
| 71 |
+
[
|
| 72 |
+
1
|
| 73 |
+
3
|
| 74 |
+
]
|
| 75 |
+
"""
|
| 76 |
+
return self._narwhals_series._with_compliant(
|
| 77 |
+
self._narwhals_series._compliant_series.dt.month()
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def day(self) -> SeriesT:
|
| 81 |
+
"""Extracts the day in a datetime series.
|
| 82 |
+
|
| 83 |
+
Examples:
|
| 84 |
+
>>> from datetime import datetime
|
| 85 |
+
>>> import pyarrow as pa
|
| 86 |
+
>>> import narwhals as nw
|
| 87 |
+
>>> s_native = pa.chunked_array(
|
| 88 |
+
... [[datetime(2022, 1, 1), datetime(2022, 1, 5)]]
|
| 89 |
+
... )
|
| 90 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 91 |
+
>>> s.dt.day().to_native() # doctest: +ELLIPSIS
|
| 92 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 93 |
+
[
|
| 94 |
+
[
|
| 95 |
+
1,
|
| 96 |
+
5
|
| 97 |
+
]
|
| 98 |
+
]
|
| 99 |
+
"""
|
| 100 |
+
return self._narwhals_series._with_compliant(
|
| 101 |
+
self._narwhals_series._compliant_series.dt.day()
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
def hour(self) -> SeriesT:
|
| 105 |
+
"""Extracts the hour in a datetime series.
|
| 106 |
+
|
| 107 |
+
Examples:
|
| 108 |
+
>>> from datetime import datetime
|
| 109 |
+
>>> import pyarrow as pa
|
| 110 |
+
>>> import narwhals as nw
|
| 111 |
+
>>> s_native = pa.chunked_array(
|
| 112 |
+
... [[datetime(2022, 1, 1, 5, 3), datetime(2022, 1, 5, 9, 12)]]
|
| 113 |
+
... )
|
| 114 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 115 |
+
>>> s.dt.hour().to_native() # doctest: +ELLIPSIS
|
| 116 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 117 |
+
[
|
| 118 |
+
[
|
| 119 |
+
5,
|
| 120 |
+
9
|
| 121 |
+
]
|
| 122 |
+
]
|
| 123 |
+
"""
|
| 124 |
+
return self._narwhals_series._with_compliant(
|
| 125 |
+
self._narwhals_series._compliant_series.dt.hour()
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def minute(self) -> SeriesT:
|
| 129 |
+
"""Extracts the minute in a datetime series.
|
| 130 |
+
|
| 131 |
+
Examples:
|
| 132 |
+
>>> from datetime import datetime
|
| 133 |
+
>>> import pandas as pd
|
| 134 |
+
>>> import narwhals as nw
|
| 135 |
+
>>> s_native = pd.Series(
|
| 136 |
+
... [datetime(2022, 1, 1, 5, 3), datetime(2022, 1, 5, 9, 12)]
|
| 137 |
+
... )
|
| 138 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 139 |
+
>>> s.dt.minute().to_native()
|
| 140 |
+
0 3
|
| 141 |
+
1 12
|
| 142 |
+
dtype: int32
|
| 143 |
+
"""
|
| 144 |
+
return self._narwhals_series._with_compliant(
|
| 145 |
+
self._narwhals_series._compliant_series.dt.minute()
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def second(self) -> SeriesT:
|
| 149 |
+
"""Extracts the seconds in a datetime series.
|
| 150 |
+
|
| 151 |
+
Examples:
|
| 152 |
+
>>> from datetime import datetime
|
| 153 |
+
>>> import pandas as pd
|
| 154 |
+
>>> import narwhals as nw
|
| 155 |
+
>>> s_native = pd.Series(
|
| 156 |
+
... [datetime(2022, 1, 1, 5, 3, 10), datetime(2022, 1, 5, 9, 12, 4)]
|
| 157 |
+
... )
|
| 158 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 159 |
+
>>> s.dt.second().to_native()
|
| 160 |
+
0 10
|
| 161 |
+
1 4
|
| 162 |
+
dtype: int32
|
| 163 |
+
"""
|
| 164 |
+
return self._narwhals_series._with_compliant(
|
| 165 |
+
self._narwhals_series._compliant_series.dt.second()
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
def millisecond(self) -> SeriesT:
|
| 169 |
+
"""Extracts the milliseconds in a datetime series.
|
| 170 |
+
|
| 171 |
+
Examples:
|
| 172 |
+
>>> from datetime import datetime
|
| 173 |
+
>>> import pandas as pd
|
| 174 |
+
>>> import narwhals as nw
|
| 175 |
+
>>> s_native = pd.Series(
|
| 176 |
+
... [
|
| 177 |
+
... datetime(2022, 1, 1, 5, 3, 7, 400000),
|
| 178 |
+
... datetime(2022, 1, 1, 5, 3, 7, 0),
|
| 179 |
+
... ]
|
| 180 |
+
... )
|
| 181 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 182 |
+
>>> s.dt.millisecond().alias("datetime").to_native()
|
| 183 |
+
0 400
|
| 184 |
+
1 0
|
| 185 |
+
Name: datetime, dtype: int32
|
| 186 |
+
"""
|
| 187 |
+
return self._narwhals_series._with_compliant(
|
| 188 |
+
self._narwhals_series._compliant_series.dt.millisecond()
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
def microsecond(self) -> SeriesT:
|
| 192 |
+
"""Extracts the microseconds in a datetime series.
|
| 193 |
+
|
| 194 |
+
Examples:
|
| 195 |
+
>>> from datetime import datetime
|
| 196 |
+
>>> import pandas as pd
|
| 197 |
+
>>> import narwhals as nw
|
| 198 |
+
>>> s_native = pd.Series(
|
| 199 |
+
... [
|
| 200 |
+
... datetime(2022, 1, 1, 5, 3, 7, 400000),
|
| 201 |
+
... datetime(2022, 1, 1, 5, 3, 7, 0),
|
| 202 |
+
... ]
|
| 203 |
+
... )
|
| 204 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 205 |
+
>>> s.dt.microsecond().alias("datetime").to_native()
|
| 206 |
+
0 400000
|
| 207 |
+
1 0
|
| 208 |
+
Name: datetime, dtype: int32
|
| 209 |
+
"""
|
| 210 |
+
return self._narwhals_series._with_compliant(
|
| 211 |
+
self._narwhals_series._compliant_series.dt.microsecond()
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def nanosecond(self) -> SeriesT:
|
| 215 |
+
"""Extract the nanoseconds in a date series.
|
| 216 |
+
|
| 217 |
+
Examples:
|
| 218 |
+
>>> from datetime import datetime
|
| 219 |
+
>>> import pandas as pd
|
| 220 |
+
>>> import narwhals as nw
|
| 221 |
+
>>> s_native = pd.Series(
|
| 222 |
+
... [
|
| 223 |
+
... datetime(2022, 1, 1, 5, 3, 7, 400000),
|
| 224 |
+
... datetime(2022, 1, 1, 5, 3, 7, 0),
|
| 225 |
+
... ]
|
| 226 |
+
... )
|
| 227 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 228 |
+
>>> s.dt.nanosecond().alias("datetime").to_native()
|
| 229 |
+
0 400000000
|
| 230 |
+
1 0
|
| 231 |
+
Name: datetime, dtype: int32
|
| 232 |
+
"""
|
| 233 |
+
return self._narwhals_series._with_compliant(
|
| 234 |
+
self._narwhals_series._compliant_series.dt.nanosecond()
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
def ordinal_day(self) -> SeriesT:
|
| 238 |
+
"""Get ordinal day.
|
| 239 |
+
|
| 240 |
+
Examples:
|
| 241 |
+
>>> from datetime import datetime
|
| 242 |
+
>>> import pyarrow as pa
|
| 243 |
+
>>> import narwhals as nw
|
| 244 |
+
>>> s_native = pa.chunked_array(
|
| 245 |
+
... [[datetime(2020, 1, 1), datetime(2020, 8, 3)]]
|
| 246 |
+
... )
|
| 247 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 248 |
+
>>> s.dt.ordinal_day().to_native() # doctest: +ELLIPSIS
|
| 249 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 250 |
+
[
|
| 251 |
+
[
|
| 252 |
+
1,
|
| 253 |
+
216
|
| 254 |
+
]
|
| 255 |
+
]
|
| 256 |
+
"""
|
| 257 |
+
return self._narwhals_series._with_compliant(
|
| 258 |
+
self._narwhals_series._compliant_series.dt.ordinal_day()
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
def weekday(self) -> SeriesT:
|
| 262 |
+
"""Extract the week day in a datetime series.
|
| 263 |
+
|
| 264 |
+
Note that Monday = 1 and Sunday = 7.
|
| 265 |
+
|
| 266 |
+
Examples:
|
| 267 |
+
>>> from datetime import datetime
|
| 268 |
+
>>> import pyarrow as pa
|
| 269 |
+
>>> import narwhals as nw
|
| 270 |
+
>>> s_native = pa.chunked_array(
|
| 271 |
+
... [[datetime(2020, 1, 1), datetime(2020, 8, 3)]]
|
| 272 |
+
... )
|
| 273 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 274 |
+
>>> s.dt.weekday().to_native() # doctest: +ELLIPSIS
|
| 275 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 276 |
+
[
|
| 277 |
+
[
|
| 278 |
+
3,
|
| 279 |
+
1
|
| 280 |
+
]
|
| 281 |
+
]
|
| 282 |
+
"""
|
| 283 |
+
return self._narwhals_series._with_compliant(
|
| 284 |
+
self._narwhals_series._compliant_series.dt.weekday()
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
def total_minutes(self) -> SeriesT:
|
| 288 |
+
"""Get total minutes.
|
| 289 |
+
|
| 290 |
+
Notes:
|
| 291 |
+
The function outputs the total minutes in the int dtype by default,
|
| 292 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 293 |
+
consider using `fill_null()` in this case.
|
| 294 |
+
|
| 295 |
+
Examples:
|
| 296 |
+
>>> from datetime import timedelta
|
| 297 |
+
>>> import polars as pl
|
| 298 |
+
>>> import narwhals as nw
|
| 299 |
+
>>> s_native = pl.Series(
|
| 300 |
+
... [timedelta(minutes=10), timedelta(minutes=20, seconds=40)]
|
| 301 |
+
... )
|
| 302 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 303 |
+
>>> s.dt.total_minutes().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 304 |
+
shape: (2,)
|
| 305 |
+
Series: '' [i64]
|
| 306 |
+
[
|
| 307 |
+
10
|
| 308 |
+
20
|
| 309 |
+
]
|
| 310 |
+
"""
|
| 311 |
+
return self._narwhals_series._with_compliant(
|
| 312 |
+
self._narwhals_series._compliant_series.dt.total_minutes()
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
def total_seconds(self) -> SeriesT:
|
| 316 |
+
"""Get total seconds.
|
| 317 |
+
|
| 318 |
+
Notes:
|
| 319 |
+
The function outputs the total seconds in the int dtype by default,
|
| 320 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 321 |
+
consider using `fill_null()` in this case.
|
| 322 |
+
|
| 323 |
+
Examples:
|
| 324 |
+
>>> from datetime import timedelta
|
| 325 |
+
>>> import polars as pl
|
| 326 |
+
>>> import narwhals as nw
|
| 327 |
+
>>> s_native = pl.Series(
|
| 328 |
+
... [timedelta(minutes=10), timedelta(minutes=20, seconds=40)]
|
| 329 |
+
... )
|
| 330 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 331 |
+
>>> s.dt.total_seconds().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 332 |
+
shape: (2,)
|
| 333 |
+
Series: '' [i64]
|
| 334 |
+
[
|
| 335 |
+
600
|
| 336 |
+
1240
|
| 337 |
+
]
|
| 338 |
+
"""
|
| 339 |
+
return self._narwhals_series._with_compliant(
|
| 340 |
+
self._narwhals_series._compliant_series.dt.total_seconds()
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
def total_milliseconds(self) -> SeriesT:
|
| 344 |
+
"""Get total milliseconds.
|
| 345 |
+
|
| 346 |
+
Notes:
|
| 347 |
+
The function outputs the total milliseconds in the int dtype by default,
|
| 348 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 349 |
+
consider using `fill_null()` in this case.
|
| 350 |
+
|
| 351 |
+
Examples:
|
| 352 |
+
>>> from datetime import timedelta
|
| 353 |
+
>>> import polars as pl
|
| 354 |
+
>>> import narwhals as nw
|
| 355 |
+
>>> s_native = pl.Series(
|
| 356 |
+
... [
|
| 357 |
+
... timedelta(milliseconds=10),
|
| 358 |
+
... timedelta(milliseconds=20, microseconds=40),
|
| 359 |
+
... ]
|
| 360 |
+
... )
|
| 361 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 362 |
+
>>> s.dt.total_milliseconds().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 363 |
+
shape: (2,)
|
| 364 |
+
Series: '' [i64]
|
| 365 |
+
[
|
| 366 |
+
10
|
| 367 |
+
20
|
| 368 |
+
]
|
| 369 |
+
"""
|
| 370 |
+
return self._narwhals_series._with_compliant(
|
| 371 |
+
self._narwhals_series._compliant_series.dt.total_milliseconds()
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
def total_microseconds(self) -> SeriesT:
|
| 375 |
+
"""Get total microseconds.
|
| 376 |
+
|
| 377 |
+
Notes:
|
| 378 |
+
The function outputs the total microseconds in the int dtype by default,
|
| 379 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 380 |
+
consider using `fill_null()` in this case.
|
| 381 |
+
|
| 382 |
+
Examples:
|
| 383 |
+
>>> from datetime import timedelta
|
| 384 |
+
>>> import polars as pl
|
| 385 |
+
>>> import narwhals as nw
|
| 386 |
+
>>> s_native = pl.Series(
|
| 387 |
+
... [
|
| 388 |
+
... timedelta(microseconds=10),
|
| 389 |
+
... timedelta(milliseconds=1, microseconds=200),
|
| 390 |
+
... ]
|
| 391 |
+
... )
|
| 392 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 393 |
+
>>> s.dt.total_microseconds().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 394 |
+
shape: (2,)
|
| 395 |
+
Series: '' [i64]
|
| 396 |
+
[
|
| 397 |
+
10
|
| 398 |
+
1200
|
| 399 |
+
]
|
| 400 |
+
"""
|
| 401 |
+
return self._narwhals_series._with_compliant(
|
| 402 |
+
self._narwhals_series._compliant_series.dt.total_microseconds()
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
def total_nanoseconds(self) -> SeriesT:
|
| 406 |
+
"""Get total nanoseconds.
|
| 407 |
+
|
| 408 |
+
Notes:
|
| 409 |
+
The function outputs the total nanoseconds in the int dtype by default,
|
| 410 |
+
however, pandas may change the dtype to float when there are missing values,
|
| 411 |
+
consider using `fill_null()` in this case.
|
| 412 |
+
|
| 413 |
+
Examples:
|
| 414 |
+
>>> from datetime import datetime
|
| 415 |
+
>>> import polars as pl
|
| 416 |
+
>>> import narwhals as nw
|
| 417 |
+
>>> s_native = pl.Series(
|
| 418 |
+
... ["2024-01-01 00:00:00.000000001", "2024-01-01 00:00:00.000000002"]
|
| 419 |
+
... ).str.to_datetime(time_unit="ns")
|
| 420 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 421 |
+
>>> s.diff().dt.total_nanoseconds().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 422 |
+
shape: (2,)
|
| 423 |
+
Series: '' [i64]
|
| 424 |
+
[
|
| 425 |
+
null
|
| 426 |
+
1
|
| 427 |
+
]
|
| 428 |
+
"""
|
| 429 |
+
return self._narwhals_series._with_compliant(
|
| 430 |
+
self._narwhals_series._compliant_series.dt.total_nanoseconds()
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
def to_string(self, format: str) -> SeriesT:
|
| 434 |
+
"""Convert a Date/Time/Datetime series into a String series with the given format.
|
| 435 |
+
|
| 436 |
+
Arguments:
|
| 437 |
+
format: Format string for converting the datetime to string.
|
| 438 |
+
|
| 439 |
+
Notes:
|
| 440 |
+
Unfortunately, different libraries interpret format directives a bit
|
| 441 |
+
differently.
|
| 442 |
+
|
| 443 |
+
- Chrono, the library used by Polars, uses `"%.f"` for fractional seconds,
|
| 444 |
+
whereas pandas and Python stdlib use `".%f"`.
|
| 445 |
+
- PyArrow interprets `"%S"` as "seconds, including fractional seconds"
|
| 446 |
+
whereas most other tools interpret it as "just seconds, as 2 digits".
|
| 447 |
+
---
|
| 448 |
+
Therefore, we make the following adjustments.
|
| 449 |
+
|
| 450 |
+
- for pandas-like libraries, we replace `"%S.%f"` with `"%S%.f"`.
|
| 451 |
+
- for PyArrow, we replace `"%S.%f"` with `"%S"`.
|
| 452 |
+
---
|
| 453 |
+
Workarounds like these don't make us happy, and we try to avoid them as
|
| 454 |
+
much as possible, but here we feel like it's the best compromise.
|
| 455 |
+
|
| 456 |
+
If you just want to format a date/datetime Series as a local datetime
|
| 457 |
+
string, and have it work as consistently as possible across libraries,
|
| 458 |
+
we suggest using:
|
| 459 |
+
|
| 460 |
+
- `"%Y-%m-%dT%H:%M:%S%.f"` for datetimes
|
| 461 |
+
- `"%Y-%m-%d"` for dates
|
| 462 |
+
---
|
| 463 |
+
Though note that, even then, different tools may return a different number
|
| 464 |
+
of trailing zeros. Nonetheless, this is probably consistent enough for
|
| 465 |
+
most applications.
|
| 466 |
+
|
| 467 |
+
If you have an application where this is not enough, please open an issue
|
| 468 |
+
and let us know.
|
| 469 |
+
|
| 470 |
+
Examples:
|
| 471 |
+
>>> from datetime import datetime
|
| 472 |
+
>>> import pandas as pd
|
| 473 |
+
>>> import narwhals as nw
|
| 474 |
+
>>> s_native = pd.Series([datetime(2020, 3, 1), datetime(2020, 4, 1)])
|
| 475 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 476 |
+
>>> s.dt.to_string("%Y/%m/%d")
|
| 477 |
+
┌───────────────┐
|
| 478 |
+
|Narwhals Series|
|
| 479 |
+
|---------------|
|
| 480 |
+
|0 2020/03/01|
|
| 481 |
+
|1 2020/04/01|
|
| 482 |
+
|dtype: str |
|
| 483 |
+
└───────────────┘
|
| 484 |
+
"""
|
| 485 |
+
return self._narwhals_series._with_compliant(
|
| 486 |
+
self._narwhals_series._compliant_series.dt.to_string(format)
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
def replace_time_zone(self, time_zone: str | None) -> SeriesT:
|
| 490 |
+
"""Replace time zone.
|
| 491 |
+
|
| 492 |
+
Arguments:
|
| 493 |
+
time_zone: Target time zone.
|
| 494 |
+
|
| 495 |
+
Examples:
|
| 496 |
+
>>> from datetime import datetime, timezone
|
| 497 |
+
>>> import polars as pl
|
| 498 |
+
>>> import narwhals as nw
|
| 499 |
+
>>> s_native = pl.Series(
|
| 500 |
+
... [
|
| 501 |
+
... datetime(2024, 1, 1, tzinfo=timezone.utc),
|
| 502 |
+
... datetime(2024, 1, 2, tzinfo=timezone.utc),
|
| 503 |
+
... ]
|
| 504 |
+
... )
|
| 505 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 506 |
+
>>> s.dt.replace_time_zone(
|
| 507 |
+
... "Asia/Kathmandu"
|
| 508 |
+
... ).to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 509 |
+
shape: (2,)
|
| 510 |
+
Series: '' [datetime[μs, Asia/Kathmandu]]
|
| 511 |
+
[
|
| 512 |
+
2024-01-01 00:00:00 +0545
|
| 513 |
+
2024-01-02 00:00:00 +0545
|
| 514 |
+
]
|
| 515 |
+
"""
|
| 516 |
+
return self._narwhals_series._with_compliant(
|
| 517 |
+
self._narwhals_series._compliant_series.dt.replace_time_zone(time_zone)
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
def convert_time_zone(self, time_zone: str) -> SeriesT:
|
| 521 |
+
"""Convert time zone.
|
| 522 |
+
|
| 523 |
+
If converting from a time-zone-naive column, then conversion happens
|
| 524 |
+
as if converting from UTC.
|
| 525 |
+
|
| 526 |
+
Arguments:
|
| 527 |
+
time_zone: Target time zone.
|
| 528 |
+
|
| 529 |
+
Examples:
|
| 530 |
+
>>> from datetime import datetime, timezone
|
| 531 |
+
>>> import pandas as pd
|
| 532 |
+
>>> import narwhals as nw
|
| 533 |
+
>>> s_native = pd.Series(
|
| 534 |
+
... [
|
| 535 |
+
... datetime(2024, 1, 1, tzinfo=timezone.utc),
|
| 536 |
+
... datetime(2024, 1, 2, tzinfo=timezone.utc),
|
| 537 |
+
... ]
|
| 538 |
+
... )
|
| 539 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 540 |
+
>>> s.dt.convert_time_zone("Asia/Kathmandu").to_native()
|
| 541 |
+
0 2024-01-01 05:45:00+05:45
|
| 542 |
+
1 2024-01-02 05:45:00+05:45
|
| 543 |
+
dtype: datetime64[us, Asia/Kathmandu]
|
| 544 |
+
"""
|
| 545 |
+
if time_zone is None:
|
| 546 |
+
msg = "Target `time_zone` cannot be `None` in `convert_time_zone`. Please use `replace_time_zone(None)` if you want to remove the time zone."
|
| 547 |
+
raise TypeError(msg)
|
| 548 |
+
return self._narwhals_series._with_compliant(
|
| 549 |
+
self._narwhals_series._compliant_series.dt.convert_time_zone(time_zone)
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
def timestamp(self, time_unit: TimeUnit) -> SeriesT:
|
| 553 |
+
"""Return a timestamp in the given time unit.
|
| 554 |
+
|
| 555 |
+
Arguments:
|
| 556 |
+
time_unit: One of
|
| 557 |
+
- 'ns': nanosecond.
|
| 558 |
+
- 'us': microsecond.
|
| 559 |
+
- 'ms': millisecond.
|
| 560 |
+
|
| 561 |
+
Examples:
|
| 562 |
+
>>> from datetime import date
|
| 563 |
+
>>> import pandas as pd
|
| 564 |
+
>>> import narwhals as nw
|
| 565 |
+
>>> s_native = pd.Series(
|
| 566 |
+
... [date(2001, 1, 1), None, date(2001, 1, 3)], dtype="datetime64[ns]"
|
| 567 |
+
... )
|
| 568 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 569 |
+
>>> s.dt.timestamp("ms").to_native()
|
| 570 |
+
0 9.783072e+11
|
| 571 |
+
1 NaN
|
| 572 |
+
2 9.784800e+11
|
| 573 |
+
dtype: float64
|
| 574 |
+
"""
|
| 575 |
+
if time_unit not in {"ns", "us", "ms"}:
|
| 576 |
+
msg = (
|
| 577 |
+
"invalid `time_unit`"
|
| 578 |
+
f"\n\nExpected one of {{'ns', 'us', 'ms'}}, got {time_unit!r}."
|
| 579 |
+
)
|
| 580 |
+
raise ValueError(msg)
|
| 581 |
+
return self._narwhals_series._with_compliant(
|
| 582 |
+
self._narwhals_series._compliant_series.dt.timestamp(time_unit)
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
def truncate(self, every: str) -> SeriesT:
|
| 586 |
+
"""Divide the date/datetime range into buckets.
|
| 587 |
+
|
| 588 |
+
Arguments:
|
| 589 |
+
every: Length of bucket. Must be of form `<multiple><unit>`,
|
| 590 |
+
where `multiple` is a positive integer and `unit` is one of
|
| 591 |
+
|
| 592 |
+
- 'ns': nanosecond.
|
| 593 |
+
- 'us': microsecond.
|
| 594 |
+
- 'ms': millisecond.
|
| 595 |
+
- 's': second.
|
| 596 |
+
- 'm': minute.
|
| 597 |
+
- 'h': hour.
|
| 598 |
+
- 'd': day.
|
| 599 |
+
- 'mo': month.
|
| 600 |
+
- 'q': quarter.
|
| 601 |
+
- 'y': year.
|
| 602 |
+
|
| 603 |
+
Examples:
|
| 604 |
+
>>> from datetime import datetime
|
| 605 |
+
>>> import pandas as pd
|
| 606 |
+
>>> import narwhals as nw
|
| 607 |
+
>>> s_native = pd.Series([datetime(2021, 3, 1, 12, 34)])
|
| 608 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 609 |
+
>>> s.dt.truncate("1h").to_native()
|
| 610 |
+
0 2021-03-01 12:00:00
|
| 611 |
+
dtype: datetime64[us]
|
| 612 |
+
"""
|
| 613 |
+
return self._narwhals_series._with_compliant(
|
| 614 |
+
self._narwhals_series._compliant_series.dt.truncate(every)
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
def offset_by(self, by: str) -> SeriesT:
|
| 618 |
+
"""Offset this date by a relative time offset.
|
| 619 |
+
|
| 620 |
+
Arguments:
|
| 621 |
+
by: The offset. Must be of form `<multiple><unit>`,
|
| 622 |
+
where `multiple` is a positive integer and `unit` is one of
|
| 623 |
+
|
| 624 |
+
- 'ns': nanosecond.
|
| 625 |
+
- 'us': microsecond.
|
| 626 |
+
- 'ms': millisecond.
|
| 627 |
+
- 's': second.
|
| 628 |
+
- 'm': minute.
|
| 629 |
+
- 'h': hour.
|
| 630 |
+
- 'd': day.
|
| 631 |
+
- 'mo': month.
|
| 632 |
+
- 'q': quarter.
|
| 633 |
+
- 'y': year.
|
| 634 |
+
|
| 635 |
+
Examples:
|
| 636 |
+
>>> from datetime import datetime
|
| 637 |
+
>>> import pandas as pd
|
| 638 |
+
>>> import narwhals as nw
|
| 639 |
+
>>> s_native = pd.Series([datetime(2021, 3, 1, 12, 34)])
|
| 640 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 641 |
+
>>> s.dt.offset_by("1h").to_native()
|
| 642 |
+
0 2021-03-01 13:34:00
|
| 643 |
+
dtype: datetime64[us]
|
| 644 |
+
"""
|
| 645 |
+
return self._narwhals_series._with_compliant(
|
| 646 |
+
self._narwhals_series._compliant_series.dt.offset_by(by)
|
| 647 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/series_list.py
ADDED
|
@@ -0,0 +1,247 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Generic
|
| 4 |
+
|
| 5 |
+
from narwhals.typing import SeriesT
|
| 6 |
+
|
| 7 |
+
if TYPE_CHECKING:
|
| 8 |
+
from narwhals.typing import NonNestedLiteral
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SeriesListNamespace(Generic[SeriesT]):
|
| 12 |
+
def __init__(self, series: SeriesT) -> None:
|
| 13 |
+
self._narwhals_series = series
|
| 14 |
+
|
| 15 |
+
def len(self) -> SeriesT:
|
| 16 |
+
"""Return the number of elements in each list.
|
| 17 |
+
|
| 18 |
+
Null values count towards the total.
|
| 19 |
+
|
| 20 |
+
Examples:
|
| 21 |
+
>>> import pyarrow as pa
|
| 22 |
+
>>> import narwhals as nw
|
| 23 |
+
>>> s_native = pa.chunked_array([[[1, 2], [3, 4, None], None, []]])
|
| 24 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 25 |
+
>>> s.list.len().to_native() # doctest: +ELLIPSIS
|
| 26 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 27 |
+
[
|
| 28 |
+
[
|
| 29 |
+
2,
|
| 30 |
+
3,
|
| 31 |
+
null,
|
| 32 |
+
0
|
| 33 |
+
]
|
| 34 |
+
]
|
| 35 |
+
"""
|
| 36 |
+
return self._narwhals_series._with_compliant(
|
| 37 |
+
self._narwhals_series._compliant_series.list.len()
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
def unique(self) -> SeriesT:
|
| 41 |
+
"""Get the unique/distinct values in the list.
|
| 42 |
+
|
| 43 |
+
Null values are included in the result. The order of unique values is not guaranteed.
|
| 44 |
+
|
| 45 |
+
Examples:
|
| 46 |
+
>>> import polars as pl
|
| 47 |
+
>>> import narwhals as nw
|
| 48 |
+
>>> s_native = pl.Series([[1, 1, 2], [3, 3, None], None, []])
|
| 49 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 50 |
+
>>> s.list.unique().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 51 |
+
shape: (4,)
|
| 52 |
+
Series: '' [list[i64]]
|
| 53 |
+
[
|
| 54 |
+
[1, 2]
|
| 55 |
+
[null, 3]
|
| 56 |
+
null
|
| 57 |
+
[]
|
| 58 |
+
]
|
| 59 |
+
"""
|
| 60 |
+
return self._narwhals_series._with_compliant(
|
| 61 |
+
self._narwhals_series._compliant_series.list.unique()
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def contains(self, item: NonNestedLiteral) -> SeriesT:
|
| 65 |
+
"""Check if sublists contain the given item.
|
| 66 |
+
|
| 67 |
+
Arguments:
|
| 68 |
+
item: Item that will be checked for membership.
|
| 69 |
+
|
| 70 |
+
Examples:
|
| 71 |
+
>>> import polars as pl
|
| 72 |
+
>>> import narwhals as nw
|
| 73 |
+
>>> s_native = pl.Series([[1, 2], None, []])
|
| 74 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 75 |
+
>>> s.list.contains(1).to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 76 |
+
shape: (3,)
|
| 77 |
+
Series: '' [bool]
|
| 78 |
+
[
|
| 79 |
+
true
|
| 80 |
+
null
|
| 81 |
+
false
|
| 82 |
+
]
|
| 83 |
+
"""
|
| 84 |
+
return self._narwhals_series._with_compliant(
|
| 85 |
+
self._narwhals_series._compliant_series.list.contains(item)
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def get(self, index: int) -> SeriesT:
|
| 89 |
+
"""Return the value by index in each list.
|
| 90 |
+
|
| 91 |
+
Negative indices are not accepted.
|
| 92 |
+
|
| 93 |
+
Examples:
|
| 94 |
+
>>> import polars as pl
|
| 95 |
+
>>> import narwhals as nw
|
| 96 |
+
>>> s_native = pl.Series([[1, 2], [3, 4, None], [None, 5]])
|
| 97 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 98 |
+
>>> s.list.get(1).to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 99 |
+
shape: (3,)
|
| 100 |
+
Series: '' [i64]
|
| 101 |
+
[
|
| 102 |
+
2
|
| 103 |
+
4
|
| 104 |
+
5
|
| 105 |
+
]
|
| 106 |
+
"""
|
| 107 |
+
if not isinstance(index, int):
|
| 108 |
+
msg = (
|
| 109 |
+
f"Index must be of type 'int'. Got type '{type(index).__name__}' instead."
|
| 110 |
+
)
|
| 111 |
+
raise TypeError(msg)
|
| 112 |
+
|
| 113 |
+
if index < 0:
|
| 114 |
+
msg = f"Index {index} is out of bounds: should be greater than or equal to 0."
|
| 115 |
+
raise ValueError(msg)
|
| 116 |
+
|
| 117 |
+
return self._narwhals_series._with_compliant(
|
| 118 |
+
self._narwhals_series._compliant_series.list.get(index)
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
def min(self) -> SeriesT:
|
| 122 |
+
"""Compute the min value of the lists in the array.
|
| 123 |
+
|
| 124 |
+
Examples:
|
| 125 |
+
>>> import polars as pl
|
| 126 |
+
>>> import narwhals as nw
|
| 127 |
+
>>> s_native = pl.Series([[1], [3, 4, None]])
|
| 128 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 129 |
+
>>> s.list.min().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 130 |
+
shape: (2,)
|
| 131 |
+
Series: '' [i64]
|
| 132 |
+
[
|
| 133 |
+
1
|
| 134 |
+
3
|
| 135 |
+
]
|
| 136 |
+
"""
|
| 137 |
+
return self._narwhals_series._with_compliant(
|
| 138 |
+
self._narwhals_series._compliant_series.list.min()
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
def max(self) -> SeriesT:
|
| 142 |
+
"""Compute the max value of the lists in the array.
|
| 143 |
+
|
| 144 |
+
Examples:
|
| 145 |
+
>>> import pyarrow as pa
|
| 146 |
+
>>> import narwhals as nw
|
| 147 |
+
>>> s_native = pa.chunked_array([[[1], [3, 4, None]]])
|
| 148 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 149 |
+
>>> s.list.max().to_native() # doctest: +ELLIPSIS
|
| 150 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 151 |
+
[
|
| 152 |
+
[
|
| 153 |
+
1,
|
| 154 |
+
4
|
| 155 |
+
]
|
| 156 |
+
]
|
| 157 |
+
"""
|
| 158 |
+
return self._narwhals_series._with_compliant(
|
| 159 |
+
self._narwhals_series._compliant_series.list.max()
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def mean(self) -> SeriesT:
|
| 163 |
+
"""Compute the mean value of the lists in the array.
|
| 164 |
+
|
| 165 |
+
Examples:
|
| 166 |
+
>>> import polars as pl
|
| 167 |
+
>>> import narwhals as nw
|
| 168 |
+
>>> s_native = pl.Series([[1], [3, 4, None]])
|
| 169 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 170 |
+
>>> s.list.mean().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 171 |
+
shape: (2,)
|
| 172 |
+
Series: '' [f64]
|
| 173 |
+
[
|
| 174 |
+
1.0
|
| 175 |
+
3.5
|
| 176 |
+
]
|
| 177 |
+
"""
|
| 178 |
+
return self._narwhals_series._with_compliant(
|
| 179 |
+
self._narwhals_series._compliant_series.list.mean()
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def median(self) -> SeriesT:
|
| 183 |
+
"""Compute the median value of the lists in the array.
|
| 184 |
+
|
| 185 |
+
Examples:
|
| 186 |
+
>>> import pyarrow as pa
|
| 187 |
+
>>> import narwhals as nw
|
| 188 |
+
>>> s_native = pa.chunked_array([[[1], [3, 4, None]]])
|
| 189 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 190 |
+
>>> s.list.median().to_native() # doctest: +ELLIPSIS
|
| 191 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 192 |
+
[
|
| 193 |
+
[
|
| 194 |
+
1,
|
| 195 |
+
3
|
| 196 |
+
]
|
| 197 |
+
]
|
| 198 |
+
"""
|
| 199 |
+
return self._narwhals_series._with_compliant(
|
| 200 |
+
self._narwhals_series._compliant_series.list.median()
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
def sum(self) -> SeriesT:
|
| 204 |
+
"""Compute the sum value of the lists in the array.
|
| 205 |
+
|
| 206 |
+
Examples:
|
| 207 |
+
>>> import polars as pl
|
| 208 |
+
>>> import narwhals as nw
|
| 209 |
+
>>> s_native = pl.Series([[1], [3, 4, None]])
|
| 210 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 211 |
+
>>> s.list.sum().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 212 |
+
shape: (2,)
|
| 213 |
+
Series: '' [i64]
|
| 214 |
+
[
|
| 215 |
+
1
|
| 216 |
+
7
|
| 217 |
+
]
|
| 218 |
+
"""
|
| 219 |
+
return self._narwhals_series._with_compliant(
|
| 220 |
+
self._narwhals_series._compliant_series.list.sum()
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
def sort(self, *, descending: bool = False, nulls_last: bool = False) -> SeriesT:
|
| 224 |
+
"""Sort the lists of the series.
|
| 225 |
+
|
| 226 |
+
Arguments:
|
| 227 |
+
descending: Sort in descending order.
|
| 228 |
+
nulls_last: Place null values last.
|
| 229 |
+
|
| 230 |
+
Examples:
|
| 231 |
+
>>> import polars as pl
|
| 232 |
+
>>> import narwhals as nw
|
| 233 |
+
>>> s_native = pl.Series([[2, -1, 1], [3, -4, None]])
|
| 234 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 235 |
+
>>> s.list.sort().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 236 |
+
shape: (2,)
|
| 237 |
+
Series: '' [list[i64]]
|
| 238 |
+
[
|
| 239 |
+
[-1, 1, 2]
|
| 240 |
+
[null, -4, 3]
|
| 241 |
+
]
|
| 242 |
+
"""
|
| 243 |
+
return self._narwhals_series._with_compliant(
|
| 244 |
+
self._narwhals_series._compliant_series.list.sort(
|
| 245 |
+
descending=descending, nulls_last=nulls_last
|
| 246 |
+
)
|
| 247 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/series_str.py
ADDED
|
@@ -0,0 +1,519 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Generic
|
| 4 |
+
|
| 5 |
+
from narwhals.dependencies import is_narwhals_series
|
| 6 |
+
from narwhals.typing import SeriesT
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class SeriesStringNamespace(Generic[SeriesT]):
|
| 10 |
+
def __init__(self, series: SeriesT) -> None:
|
| 11 |
+
self._narwhals_series = series
|
| 12 |
+
|
| 13 |
+
def len_chars(self) -> SeriesT:
|
| 14 |
+
r"""Return the length of each string as the number of characters.
|
| 15 |
+
|
| 16 |
+
Examples:
|
| 17 |
+
>>> import polars as pl
|
| 18 |
+
>>> import narwhals as nw
|
| 19 |
+
>>> s_native = pl.Series(["foo", "345", None])
|
| 20 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 21 |
+
>>> s.str.len_chars().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 22 |
+
shape: (3,)
|
| 23 |
+
Series: '' [u32]
|
| 24 |
+
[
|
| 25 |
+
3
|
| 26 |
+
3
|
| 27 |
+
null
|
| 28 |
+
]
|
| 29 |
+
"""
|
| 30 |
+
return self._narwhals_series._with_compliant(
|
| 31 |
+
self._narwhals_series._compliant_series.str.len_chars()
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def _extract_compliant(self, arg: Any) -> Any:
|
| 35 |
+
return arg._compliant_series if is_narwhals_series(arg) else arg
|
| 36 |
+
|
| 37 |
+
def replace(
|
| 38 |
+
self, pattern: str, value: str | SeriesT, *, literal: bool = False, n: int = 1
|
| 39 |
+
) -> SeriesT:
|
| 40 |
+
r"""Replace first matching regex/literal substring with a new string value.
|
| 41 |
+
|
| 42 |
+
Arguments:
|
| 43 |
+
pattern: A valid regular expression pattern.
|
| 44 |
+
value: String that will replace the matched substring.
|
| 45 |
+
literal: Treat `pattern` as a literal string.
|
| 46 |
+
n: Number of matches to replace.
|
| 47 |
+
|
| 48 |
+
Examples:
|
| 49 |
+
>>> import pandas as pd
|
| 50 |
+
>>> import narwhals as nw
|
| 51 |
+
>>> s_native = pd.Series(["123abc", "abc abc123"])
|
| 52 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 53 |
+
>>> s.str.replace("abc", "").to_native()
|
| 54 |
+
0 123
|
| 55 |
+
1 abc123
|
| 56 |
+
dtype: str
|
| 57 |
+
"""
|
| 58 |
+
return self._narwhals_series._with_compliant(
|
| 59 |
+
self._narwhals_series._compliant_series.str.replace(
|
| 60 |
+
self._extract_compliant(value), pattern=pattern, literal=literal, n=n
|
| 61 |
+
)
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def replace_all(
|
| 65 |
+
self, pattern: str, value: str | SeriesT, *, literal: bool = False
|
| 66 |
+
) -> SeriesT:
|
| 67 |
+
r"""Replace all matching regex/literal substring with a new string value.
|
| 68 |
+
|
| 69 |
+
Arguments:
|
| 70 |
+
pattern: A valid regular expression pattern.
|
| 71 |
+
value: String that will replace the matched substring.
|
| 72 |
+
literal: Treat `pattern` as a literal string.
|
| 73 |
+
|
| 74 |
+
Examples:
|
| 75 |
+
>>> import pandas as pd
|
| 76 |
+
>>> import narwhals as nw
|
| 77 |
+
>>> s_native = pd.Series(["123abc", "abc abc123"])
|
| 78 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 79 |
+
>>> s.str.replace_all("abc", "").to_native()
|
| 80 |
+
0 123
|
| 81 |
+
1 123
|
| 82 |
+
dtype: str
|
| 83 |
+
"""
|
| 84 |
+
return self._narwhals_series._with_compliant(
|
| 85 |
+
self._narwhals_series._compliant_series.str.replace_all(
|
| 86 |
+
self._extract_compliant(value), pattern, literal=literal
|
| 87 |
+
)
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def strip_chars(self, characters: str | None = None) -> SeriesT:
|
| 91 |
+
r"""Remove leading and trailing characters.
|
| 92 |
+
|
| 93 |
+
Arguments:
|
| 94 |
+
characters: The set of characters to be removed. All combinations of this set of characters will be stripped from the start and end of the string. If set to None (default), all leading and trailing whitespace is removed instead.
|
| 95 |
+
|
| 96 |
+
Examples:
|
| 97 |
+
>>> import polars as pl
|
| 98 |
+
>>> import narwhals as nw
|
| 99 |
+
>>> s_native = pl.Series(["apple", "\nmango"])
|
| 100 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 101 |
+
>>> s.str.strip_chars().to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 102 |
+
shape: (2,)
|
| 103 |
+
Series: '' [str]
|
| 104 |
+
[
|
| 105 |
+
"apple"
|
| 106 |
+
"mango"
|
| 107 |
+
]
|
| 108 |
+
"""
|
| 109 |
+
return self._narwhals_series._with_compliant(
|
| 110 |
+
self._narwhals_series._compliant_series.str.strip_chars(characters)
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
def starts_with(self, prefix: str) -> SeriesT:
|
| 114 |
+
r"""Check if string values start with a substring.
|
| 115 |
+
|
| 116 |
+
Arguments:
|
| 117 |
+
prefix: prefix substring
|
| 118 |
+
|
| 119 |
+
Examples:
|
| 120 |
+
>>> import pandas as pd
|
| 121 |
+
>>> import narwhals as nw
|
| 122 |
+
>>> s_native = pd.Series(["apple", "mango", None])
|
| 123 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 124 |
+
>>> s.str.starts_with("app").to_native()
|
| 125 |
+
0 True
|
| 126 |
+
1 False
|
| 127 |
+
2 False
|
| 128 |
+
dtype: bool
|
| 129 |
+
"""
|
| 130 |
+
return self._narwhals_series._with_compliant(
|
| 131 |
+
self._narwhals_series._compliant_series.str.starts_with(prefix)
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def ends_with(self, suffix: str) -> SeriesT:
|
| 135 |
+
r"""Check if string values end with a substring.
|
| 136 |
+
|
| 137 |
+
Arguments:
|
| 138 |
+
suffix: suffix substring
|
| 139 |
+
|
| 140 |
+
Examples:
|
| 141 |
+
>>> import pandas as pd
|
| 142 |
+
>>> import narwhals as nw
|
| 143 |
+
>>> s_native = pd.Series(["apple", "mango", None])
|
| 144 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 145 |
+
>>> s.str.ends_with("ngo").to_native()
|
| 146 |
+
0 False
|
| 147 |
+
1 True
|
| 148 |
+
2 False
|
| 149 |
+
dtype: bool
|
| 150 |
+
"""
|
| 151 |
+
return self._narwhals_series._with_compliant(
|
| 152 |
+
self._narwhals_series._compliant_series.str.ends_with(suffix)
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def contains(self, pattern: str | SeriesT, *, literal: bool = False) -> SeriesT:
|
| 156 |
+
r"""Check if string contains a substring that matches a pattern.
|
| 157 |
+
|
| 158 |
+
Arguments:
|
| 159 |
+
pattern: A Character sequence, valid regular expression pattern, or another
|
| 160 |
+
Series.
|
| 161 |
+
literal: If True, treats the pattern as a literal string.
|
| 162 |
+
If False, assumes the pattern is a regular expression.
|
| 163 |
+
|
| 164 |
+
Warning:
|
| 165 |
+
Passing a Series as `pattern` is only supported by Polars. Other backends
|
| 166 |
+
will raise a `TypeError`.
|
| 167 |
+
|
| 168 |
+
Examples:
|
| 169 |
+
>>> import pyarrow as pa
|
| 170 |
+
>>> import narwhals as nw
|
| 171 |
+
>>> s_native = pa.chunked_array([["cat", "dog", "rabbit and parrot"]])
|
| 172 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 173 |
+
>>> s.str.contains("cat|parrot").to_native() # doctest: +ELLIPSIS
|
| 174 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 175 |
+
[
|
| 176 |
+
[
|
| 177 |
+
true,
|
| 178 |
+
false,
|
| 179 |
+
true
|
| 180 |
+
]
|
| 181 |
+
]
|
| 182 |
+
"""
|
| 183 |
+
return self._narwhals_series._with_compliant(
|
| 184 |
+
self._narwhals_series._compliant_series.str.contains(
|
| 185 |
+
self._extract_compliant(pattern), literal=literal
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
def slice(self, offset: int, length: int | None = None) -> SeriesT:
|
| 190 |
+
r"""Create subslices of the string values of a Series.
|
| 191 |
+
|
| 192 |
+
Arguments:
|
| 193 |
+
offset: Start index. Negative indexing is supported.
|
| 194 |
+
length: Length of the slice. If set to `None` (default), the slice is taken to the
|
| 195 |
+
end of the string.
|
| 196 |
+
|
| 197 |
+
Examples:
|
| 198 |
+
>>> import pandas as pd
|
| 199 |
+
>>> import narwhals as nw
|
| 200 |
+
>>> s_native = pd.Series(["pear", None, "papaya"])
|
| 201 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 202 |
+
>>> s.str.slice(4, 3).to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 203 |
+
0
|
| 204 |
+
1 NaN
|
| 205 |
+
2 ya
|
| 206 |
+
dtype: str
|
| 207 |
+
"""
|
| 208 |
+
return self._narwhals_series._with_compliant(
|
| 209 |
+
self._narwhals_series._compliant_series.str.slice(
|
| 210 |
+
offset=offset, length=length
|
| 211 |
+
)
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def split(self, by: str) -> SeriesT:
|
| 215 |
+
r"""Split the string values of a Series by a substring.
|
| 216 |
+
|
| 217 |
+
Arguments:
|
| 218 |
+
by: Substring to split by.
|
| 219 |
+
|
| 220 |
+
Examples:
|
| 221 |
+
>>> import polars as pl
|
| 222 |
+
>>> import narwhals as nw
|
| 223 |
+
>>> s_native = pl.Series(["foo bar", "foo_bar"])
|
| 224 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 225 |
+
>>> s.str.split("_").to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 226 |
+
shape: (2,)
|
| 227 |
+
Series: '' [list[str]]
|
| 228 |
+
[
|
| 229 |
+
["foo bar"]
|
| 230 |
+
["foo", "bar"]
|
| 231 |
+
]
|
| 232 |
+
"""
|
| 233 |
+
return self._narwhals_series._with_compliant(
|
| 234 |
+
self._narwhals_series._compliant_series.str.split(by=by)
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
def head(self, n: int = 5) -> SeriesT:
|
| 238 |
+
r"""Take the first n elements of each string.
|
| 239 |
+
|
| 240 |
+
Arguments:
|
| 241 |
+
n: Number of elements to take. Negative indexing is supported (see note (1.))
|
| 242 |
+
|
| 243 |
+
Notes:
|
| 244 |
+
1. When the `n` input is negative, `head` returns characters up to the n-th from the end of the string.
|
| 245 |
+
For example, if `n = -3`, then all characters except the last three are returned.
|
| 246 |
+
2. If the length of the string has fewer than `n` characters, the full string is returned.
|
| 247 |
+
|
| 248 |
+
Examples:
|
| 249 |
+
>>> import pyarrow as pa
|
| 250 |
+
>>> import narwhals as nw
|
| 251 |
+
>>> s_native = pa.chunked_array([["taata", "taatatata", "zukkyun"]])
|
| 252 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 253 |
+
>>> s.str.head().to_native() # doctest: +ELLIPSIS
|
| 254 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 255 |
+
[
|
| 256 |
+
[
|
| 257 |
+
"taata",
|
| 258 |
+
"taata",
|
| 259 |
+
"zukky"
|
| 260 |
+
]
|
| 261 |
+
]
|
| 262 |
+
"""
|
| 263 |
+
return self._narwhals_series._with_compliant(
|
| 264 |
+
self._narwhals_series._compliant_series.str.slice(offset=0, length=n)
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
def tail(self, n: int = 5) -> SeriesT:
|
| 268 |
+
r"""Take the last n elements of each string.
|
| 269 |
+
|
| 270 |
+
Arguments:
|
| 271 |
+
n: Number of elements to take. Negative indexing is supported (see note (1.))
|
| 272 |
+
|
| 273 |
+
Notes:
|
| 274 |
+
1. When the `n` input is negative, `tail` returns characters starting from the n-th from the beginning of
|
| 275 |
+
the string. For example, if `n = -3`, then all characters except the first three are returned.
|
| 276 |
+
2. If the length of the string has fewer than `n` characters, the full string is returned.
|
| 277 |
+
|
| 278 |
+
Examples:
|
| 279 |
+
>>> import pyarrow as pa
|
| 280 |
+
>>> import narwhals as nw
|
| 281 |
+
>>> s_native = pa.chunked_array([["taata", "taatatata", "zukkyun"]])
|
| 282 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 283 |
+
>>> s.str.tail().to_native() # doctest: +ELLIPSIS
|
| 284 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 285 |
+
[
|
| 286 |
+
[
|
| 287 |
+
"taata",
|
| 288 |
+
"atata",
|
| 289 |
+
"kkyun"
|
| 290 |
+
]
|
| 291 |
+
]
|
| 292 |
+
"""
|
| 293 |
+
return self._narwhals_series._with_compliant(
|
| 294 |
+
self._narwhals_series._compliant_series.str.slice(offset=-n, length=None)
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
def to_uppercase(self) -> SeriesT:
|
| 298 |
+
r"""Transform string to uppercase variant.
|
| 299 |
+
|
| 300 |
+
Notes:
|
| 301 |
+
The PyArrow backend will convert 'ß' to 'ẞ' instead of 'SS'.
|
| 302 |
+
For more info see: https://github.com/apache/arrow/issues/34599
|
| 303 |
+
There may be other unicode-edge-case-related variations across implementations.
|
| 304 |
+
|
| 305 |
+
Examples:
|
| 306 |
+
>>> import pandas as pd
|
| 307 |
+
>>> import narwhals as nw
|
| 308 |
+
>>> s_native = pd.Series(["apple", None])
|
| 309 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 310 |
+
>>> s.str.to_uppercase().to_native()
|
| 311 |
+
0 APPLE
|
| 312 |
+
1 NaN
|
| 313 |
+
dtype: str
|
| 314 |
+
"""
|
| 315 |
+
return self._narwhals_series._with_compliant(
|
| 316 |
+
self._narwhals_series._compliant_series.str.to_uppercase()
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
def to_lowercase(self) -> SeriesT:
|
| 320 |
+
r"""Transform string to lowercase variant.
|
| 321 |
+
|
| 322 |
+
Examples:
|
| 323 |
+
>>> import pandas as pd
|
| 324 |
+
>>> import narwhals as nw
|
| 325 |
+
>>> s_native = pd.Series(["APPLE", None])
|
| 326 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 327 |
+
>>> s.str.to_lowercase().to_native()
|
| 328 |
+
0 apple
|
| 329 |
+
1 NaN
|
| 330 |
+
dtype: str
|
| 331 |
+
"""
|
| 332 |
+
return self._narwhals_series._with_compliant(
|
| 333 |
+
self._narwhals_series._compliant_series.str.to_lowercase()
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
def to_datetime(self, format: str | None = None) -> SeriesT:
|
| 337 |
+
"""Parse Series with strings to a Series with Datetime dtype.
|
| 338 |
+
|
| 339 |
+
Notes:
|
| 340 |
+
- pandas defaults to nanosecond time unit, Polars to microsecond.
|
| 341 |
+
Prior to pandas 2.0, nanoseconds were the only time unit supported
|
| 342 |
+
in pandas, with no ability to set any other one. The ability to
|
| 343 |
+
set the time unit in pandas, if the version permits, will arrive.
|
| 344 |
+
- timezone-aware strings are all converted to and parsed as UTC.
|
| 345 |
+
|
| 346 |
+
Warning:
|
| 347 |
+
As different backends auto-infer format in different ways, if `format=None`
|
| 348 |
+
there is no guarantee that the result will be equal.
|
| 349 |
+
|
| 350 |
+
Arguments:
|
| 351 |
+
format: Format to use for conversion. If set to None (default), the format is
|
| 352 |
+
inferred from the data.
|
| 353 |
+
|
| 354 |
+
Examples:
|
| 355 |
+
>>> import polars as pl
|
| 356 |
+
>>> import narwhals as nw
|
| 357 |
+
>>> s_native = pl.Series(["2020-01-01", "2020-01-02"])
|
| 358 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 359 |
+
>>> s.str.to_datetime(
|
| 360 |
+
... format="%Y-%m-%d"
|
| 361 |
+
... ).to_native() # doctest: +NORMALIZE_WHITESPACE
|
| 362 |
+
shape: (2,)
|
| 363 |
+
Series: '' [datetime[μs]]
|
| 364 |
+
[
|
| 365 |
+
2020-01-01 00:00:00
|
| 366 |
+
2020-01-02 00:00:00
|
| 367 |
+
]
|
| 368 |
+
"""
|
| 369 |
+
return self._narwhals_series._with_compliant(
|
| 370 |
+
self._narwhals_series._compliant_series.str.to_datetime(format=format)
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
def to_date(self, format: str | None = None) -> SeriesT:
|
| 374 |
+
"""Convert to date dtype.
|
| 375 |
+
|
| 376 |
+
Warning:
|
| 377 |
+
As different backends auto-infer format in different ways, if `format=None`
|
| 378 |
+
there is no guarantee that the result will be equal.
|
| 379 |
+
|
| 380 |
+
Arguments:
|
| 381 |
+
format: Format to use for conversion. If set to None (default), the format is
|
| 382 |
+
inferred from the data.
|
| 383 |
+
|
| 384 |
+
Examples:
|
| 385 |
+
>>> import pyarrow as pa
|
| 386 |
+
>>> import narwhals as nw
|
| 387 |
+
>>> s_native = pa.chunked_array([["2020-01-01", "2020-01-02"]])
|
| 388 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 389 |
+
>>> s.str.to_date(format="%Y-%m-%d").to_native() # doctest: +ELLIPSIS
|
| 390 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 391 |
+
[
|
| 392 |
+
[
|
| 393 |
+
2020-01-01,
|
| 394 |
+
2020-01-02
|
| 395 |
+
]
|
| 396 |
+
]
|
| 397 |
+
"""
|
| 398 |
+
return self._narwhals_series._with_compliant(
|
| 399 |
+
self._narwhals_series._compliant_series.str.to_date(format=format)
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
def to_titlecase(self) -> SeriesT:
|
| 403 |
+
"""Modify strings to their titlecase equivalent.
|
| 404 |
+
|
| 405 |
+
Notes:
|
| 406 |
+
This is a form of case transform where the first letter of each word is
|
| 407 |
+
capitalized, with the rest of the word in lowercase.
|
| 408 |
+
|
| 409 |
+
Word boundaries are defined by non-**alphabetic** characters, matching the
|
| 410 |
+
behavior of [`str.title`](https://docs.python.org/3/library/stdtypes.html#str.title)
|
| 411 |
+
|
| 412 |
+
Examples:
|
| 413 |
+
>>> import pyarrow as pa
|
| 414 |
+
>>> import narwhals as nw
|
| 415 |
+
>>> s_native = pa.chunked_array(
|
| 416 |
+
... [
|
| 417 |
+
... [
|
| 418 |
+
... "'e.t. phone home'",
|
| 419 |
+
... "you talkin' to me?",
|
| 420 |
+
... "to infinity,and BEYOND!",
|
| 421 |
+
... ]
|
| 422 |
+
... ]
|
| 423 |
+
... )
|
| 424 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 425 |
+
>>> s.str.to_titlecase().to_native() # doctest: +ELLIPSIS
|
| 426 |
+
<pyarrow.lib.ChunkedArray object at ...>
|
| 427 |
+
[
|
| 428 |
+
[
|
| 429 |
+
"'E.T. Phone Home'",
|
| 430 |
+
"You Talkin' To Me?",
|
| 431 |
+
"To Infinity,And Beyond!"
|
| 432 |
+
]
|
| 433 |
+
]
|
| 434 |
+
"""
|
| 435 |
+
return self._narwhals_series._with_compliant(
|
| 436 |
+
self._narwhals_series._compliant_series.str.to_titlecase()
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
def zfill(self, width: int) -> SeriesT:
|
| 440 |
+
r"""Pad strings with zeros on the left.
|
| 441 |
+
|
| 442 |
+
Arguments:
|
| 443 |
+
width: The target width of the string. If the string is shorter than this width, it will be padded with zeros on the left.
|
| 444 |
+
|
| 445 |
+
Examples:
|
| 446 |
+
>>> import pandas as pd
|
| 447 |
+
>>> import narwhals as nw
|
| 448 |
+
>>> s_native = pd.Series(["+1", "-23", "456", "123456"])
|
| 449 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 450 |
+
>>> s.str.zfill(5).to_native()
|
| 451 |
+
0 +0001
|
| 452 |
+
1 -0023
|
| 453 |
+
2 00456
|
| 454 |
+
3 123456
|
| 455 |
+
dtype: str
|
| 456 |
+
"""
|
| 457 |
+
return self._narwhals_series._with_compliant(
|
| 458 |
+
self._narwhals_series._compliant_series.str.zfill(width)
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
def pad_start(self, length: int, fill_char: str = " ") -> SeriesT:
|
| 462 |
+
"""Pad the start of the string until it reaches the given length.
|
| 463 |
+
|
| 464 |
+
Arguments:
|
| 465 |
+
length: Pad the string until it reaches this length. Strings with
|
| 466 |
+
length equal to or greater than this value are returned as-is.
|
| 467 |
+
fill_char: The character to pad the string with.
|
| 468 |
+
|
| 469 |
+
Examples:
|
| 470 |
+
>>> import pandas as pd
|
| 471 |
+
>>> import narwhals as nw
|
| 472 |
+
>>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]})
|
| 473 |
+
>>> df = nw.from_native(df_native)
|
| 474 |
+
>>> df["a"].str.pad_start(8, "*")
|
| 475 |
+
┌───────────────────┐
|
| 476 |
+
| Narwhals Series |
|
| 477 |
+
|-------------------|
|
| 478 |
+
|0 *****cow |
|
| 479 |
+
|1 **monkey |
|
| 480 |
+
|2 hippopotamus |
|
| 481 |
+
|3 NaN |
|
| 482 |
+
|Name: a, dtype: str|
|
| 483 |
+
└───────────────────┘
|
| 484 |
+
"""
|
| 485 |
+
return self._narwhals_series._with_compliant(
|
| 486 |
+
self._narwhals_series._compliant_series.str.pad_start(
|
| 487 |
+
length=length, fill_char=fill_char
|
| 488 |
+
)
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
def pad_end(self, length: int, fill_char: str = " ") -> SeriesT:
|
| 492 |
+
"""Pad the end of the string until it reaches the given length.
|
| 493 |
+
|
| 494 |
+
Arguments:
|
| 495 |
+
length: Pad the string until it reaches this length. Strings with
|
| 496 |
+
length equal to or greater than this value are returned as-is.
|
| 497 |
+
fill_char: The character to pad the string with.
|
| 498 |
+
|
| 499 |
+
Examples:
|
| 500 |
+
>>> import pandas as pd
|
| 501 |
+
>>> import narwhals as nw
|
| 502 |
+
>>> df_native = pd.DataFrame({"a": ["cow", "monkey", "hippopotamus", None]})
|
| 503 |
+
>>> df = nw.from_native(df_native)
|
| 504 |
+
>>> df["a"].str.pad_end(8, "*")
|
| 505 |
+
┌───────────────────┐
|
| 506 |
+
| Narwhals Series |
|
| 507 |
+
|-------------------|
|
| 508 |
+
|0 cow***** |
|
| 509 |
+
|1 monkey** |
|
| 510 |
+
|2 hippopotamus |
|
| 511 |
+
|3 NaN |
|
| 512 |
+
|Name: a, dtype: str|
|
| 513 |
+
└───────────────────┘
|
| 514 |
+
"""
|
| 515 |
+
return self._narwhals_series._with_compliant(
|
| 516 |
+
self._narwhals_series._compliant_series.str.pad_end(
|
| 517 |
+
length=length, fill_char=fill_char
|
| 518 |
+
)
|
| 519 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/series_struct.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Generic
|
| 4 |
+
|
| 5 |
+
from narwhals.typing import SeriesT
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SeriesStructNamespace(Generic[SeriesT]):
|
| 9 |
+
def __init__(self, series: SeriesT) -> None:
|
| 10 |
+
self._narwhals_series = series
|
| 11 |
+
|
| 12 |
+
def field(self, name: str) -> SeriesT:
|
| 13 |
+
r"""Retrieve a Struct field as a new expression.
|
| 14 |
+
|
| 15 |
+
Arguments:
|
| 16 |
+
name: Name of the struct field to retrieve.
|
| 17 |
+
|
| 18 |
+
Examples:
|
| 19 |
+
>>> import polars as pl
|
| 20 |
+
>>> import narwhals as nw
|
| 21 |
+
>>> s_native = pl.Series(
|
| 22 |
+
... [{"id": "0", "name": "john"}, {"id": "1", "name": "jane"}]
|
| 23 |
+
... )
|
| 24 |
+
>>> s = nw.from_native(s_native, series_only=True)
|
| 25 |
+
>>> s.struct.field("name").to_list()
|
| 26 |
+
['john', 'jane']
|
| 27 |
+
"""
|
| 28 |
+
return self._narwhals_series._with_compliant(
|
| 29 |
+
self._narwhals_series._compliant_series.struct.field(name)
|
| 30 |
+
)
|
.venv_haddock/lib/python3.12/site-packages/narwhals/sql.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Literal
|
| 4 |
+
|
| 5 |
+
from narwhals._duckdb.utils import DeferredTimeZone, narwhals_to_native_dtype
|
| 6 |
+
from narwhals.dataframe import LazyFrame
|
| 7 |
+
from narwhals.translate import from_native
|
| 8 |
+
from narwhals.utils import Version
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from narwhals._compliant.typing import CompliantLazyFrameAny
|
| 12 |
+
from narwhals.typing import IntoSchema
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
import duckdb # ignore-banned-import
|
| 16 |
+
except ImportError as _exc: # pragma: no cover
|
| 17 |
+
msg = (
|
| 18 |
+
"`narwhals.sql` requires DuckDB to be installed.\n\n"
|
| 19 |
+
"Hint: run `pip install -U narwhals[sql]`"
|
| 20 |
+
)
|
| 21 |
+
raise ModuleNotFoundError(msg) from _exc
|
| 22 |
+
|
| 23 |
+
CONN = duckdb.connect()
|
| 24 |
+
TZ = DeferredTimeZone(
|
| 25 |
+
CONN.sql("select value from duckdb_settings() where name = 'TimeZone'")
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class SQLTable(LazyFrame[duckdb.DuckDBPyRelation]):
|
| 30 |
+
"""A LazyFrame with an additional `to_sql` method."""
|
| 31 |
+
|
| 32 |
+
def __init__(
|
| 33 |
+
self, df: CompliantLazyFrameAny, level: Literal["full", "interchange", "lazy"]
|
| 34 |
+
) -> None:
|
| 35 |
+
super().__init__(df, level=level)
|
| 36 |
+
|
| 37 |
+
def to_sql(self, *, pretty: bool = False) -> str:
|
| 38 |
+
"""Convert to SQL query.
|
| 39 |
+
|
| 40 |
+
Arguments:
|
| 41 |
+
pretty: Whether to pretty-print SQL query. If `True`, requires `sqlparse`
|
| 42 |
+
to be installed.
|
| 43 |
+
|
| 44 |
+
Examples:
|
| 45 |
+
>>> import narwhals as nw
|
| 46 |
+
>>> from narwhals.sql import table
|
| 47 |
+
>>> schema = {"date": nw.Date, "price": nw.Int64, "symbol": nw.String}
|
| 48 |
+
>>> assets = table("assets", schema)
|
| 49 |
+
>>> result = assets.filter(nw.col("price") > 100)
|
| 50 |
+
>>> print(result.to_sql())
|
| 51 |
+
SELECT * FROM main.assets WHERE (price > 100)
|
| 52 |
+
"""
|
| 53 |
+
sql_query = self.to_native().sql_query()
|
| 54 |
+
if not pretty:
|
| 55 |
+
return sql_query
|
| 56 |
+
try:
|
| 57 |
+
import sqlparse
|
| 58 |
+
except ImportError as _exc: # pragma: no cover
|
| 59 |
+
msg = (
|
| 60 |
+
"`SQLTable.to_sql` with `pretty=True`"
|
| 61 |
+
"requires `sqlparse` to be installed.\n\n"
|
| 62 |
+
"Hint: run `pip install -U narwhals[sql]`"
|
| 63 |
+
)
|
| 64 |
+
raise ModuleNotFoundError(msg) from _exc
|
| 65 |
+
return sqlparse.format(sql_query, reindent=True, keyword_case="upper") # type: ignore[no-any-return]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def table(name: str, schema: IntoSchema) -> SQLTable:
|
| 69 |
+
"""Generate standalone LazyFrame which you can use to generate SQL.
|
| 70 |
+
|
| 71 |
+
Note that this requires DuckDB to be installed.
|
| 72 |
+
|
| 73 |
+
Parameters:
|
| 74 |
+
name: Table name.
|
| 75 |
+
schema: Table schema.
|
| 76 |
+
|
| 77 |
+
Examples:
|
| 78 |
+
>>> import narwhals as nw
|
| 79 |
+
>>> from narwhals.sql import table
|
| 80 |
+
>>> schema = {"date": nw.Date, "price": nw.List(nw.Int64), "symbol": nw.String}
|
| 81 |
+
>>> table("t", schema)
|
| 82 |
+
┌────────────────────────────┐
|
| 83 |
+
| Narwhals LazyFrame |
|
| 84 |
+
|----------------------------|
|
| 85 |
+
|┌──────┬─────────┬─────────┐|
|
| 86 |
+
|│ date │ price │ symbol │|
|
| 87 |
+
|│ date │ int64[] │ varchar │|
|
| 88 |
+
|└──────┴─────────┴─────────┘|
|
| 89 |
+
| 0 rows |
|
| 90 |
+
└────────────────────────────┘
|
| 91 |
+
"""
|
| 92 |
+
column_mapping = {
|
| 93 |
+
col: narwhals_to_native_dtype(dtype, Version.MAIN, TZ)
|
| 94 |
+
for col, dtype in schema.items()
|
| 95 |
+
}
|
| 96 |
+
dtypes = ", ".join(f'"{col}" {dtype}' for col, dtype in column_mapping.items())
|
| 97 |
+
CONN.sql(f"""
|
| 98 |
+
CREATE TABLE "{name}"
|
| 99 |
+
({dtypes});
|
| 100 |
+
""")
|
| 101 |
+
lf = from_native(CONN.table(name))
|
| 102 |
+
return SQLTable(lf._compliant_frame, level=lf._level)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
__all__ = ["table"]
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/.___init__.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/.___pycache__
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/._v1
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/._v2
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from narwhals.stable import v1, v2
|
| 4 |
+
|
| 5 |
+
__all__ = ["v1", "v2"]
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/.___init__.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/.___pycache__
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/.__dtypes.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/.__namespace.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/._dependencies.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/._dtypes.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/._selectors.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/._typing.py
ADDED
|
Binary file (4.1 kB). View file
|
|
|
.venv_haddock/lib/python3.12/site-packages/narwhals/stable/v1/__init__.py
ADDED
|
@@ -0,0 +1,1156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from functools import wraps
|
| 4 |
+
from typing import TYPE_CHECKING, Any, Callable, Final, Literal, cast, overload
|
| 5 |
+
|
| 6 |
+
import narwhals as nw
|
| 7 |
+
from narwhals import exceptions, functions as nw_f
|
| 8 |
+
from narwhals._exceptions import issue_warning
|
| 9 |
+
from narwhals._expression_parsing import ExprKind, ExprNode, is_expr
|
| 10 |
+
from narwhals._typing_compat import TypeVar, assert_never
|
| 11 |
+
from narwhals._utils import (
|
| 12 |
+
Implementation,
|
| 13 |
+
Version,
|
| 14 |
+
deprecate_native_namespace,
|
| 15 |
+
generate_temporary_column_name,
|
| 16 |
+
inherit_doc,
|
| 17 |
+
is_ordered_categorical,
|
| 18 |
+
maybe_align_index,
|
| 19 |
+
maybe_convert_dtypes,
|
| 20 |
+
maybe_get_index,
|
| 21 |
+
maybe_reset_index,
|
| 22 |
+
maybe_set_index,
|
| 23 |
+
validate_strict_and_pass_though,
|
| 24 |
+
)
|
| 25 |
+
from narwhals.dataframe import DataFrame as NwDataFrame, LazyFrame as NwLazyFrame
|
| 26 |
+
from narwhals.exceptions import InvalidIntoExprError, NarwhalsUnstableWarning
|
| 27 |
+
from narwhals.expr import Expr as NwExpr
|
| 28 |
+
from narwhals.functions import _new_series_impl, concat, show_versions
|
| 29 |
+
from narwhals.schema import Schema as NwSchema
|
| 30 |
+
from narwhals.series import Series as NwSeries
|
| 31 |
+
from narwhals.stable.v1 import dependencies, dtypes, selectors
|
| 32 |
+
from narwhals.stable.v1.dtypes import (
|
| 33 |
+
Array,
|
| 34 |
+
Binary,
|
| 35 |
+
Boolean,
|
| 36 |
+
Categorical,
|
| 37 |
+
Date,
|
| 38 |
+
Datetime,
|
| 39 |
+
Decimal,
|
| 40 |
+
Duration,
|
| 41 |
+
Enum,
|
| 42 |
+
Field,
|
| 43 |
+
Float32,
|
| 44 |
+
Float64,
|
| 45 |
+
Int8,
|
| 46 |
+
Int16,
|
| 47 |
+
Int32,
|
| 48 |
+
Int64,
|
| 49 |
+
Int128,
|
| 50 |
+
List,
|
| 51 |
+
Object,
|
| 52 |
+
String,
|
| 53 |
+
Struct,
|
| 54 |
+
Time,
|
| 55 |
+
UInt8,
|
| 56 |
+
UInt16,
|
| 57 |
+
UInt32,
|
| 58 |
+
UInt64,
|
| 59 |
+
UInt128,
|
| 60 |
+
Unknown,
|
| 61 |
+
)
|
| 62 |
+
from narwhals.stable.v1.typing import (
|
| 63 |
+
DataFrameT,
|
| 64 |
+
IntoDataFrameT,
|
| 65 |
+
IntoFrame,
|
| 66 |
+
IntoLazyFrameT,
|
| 67 |
+
IntoSeries,
|
| 68 |
+
IntoSeriesT,
|
| 69 |
+
LazyFrameT,
|
| 70 |
+
SeriesT,
|
| 71 |
+
)
|
| 72 |
+
from narwhals.translate import _from_native_impl, get_native_namespace, to_py_scalar
|
| 73 |
+
|
| 74 |
+
if TYPE_CHECKING:
|
| 75 |
+
from collections.abc import Iterable, Mapping, Sequence
|
| 76 |
+
from types import ModuleType
|
| 77 |
+
|
| 78 |
+
from typing_extensions import ParamSpec, Self, Unpack
|
| 79 |
+
|
| 80 |
+
from narwhals._expression_parsing import ExprMetadata
|
| 81 |
+
from narwhals._translate import (
|
| 82 |
+
AllowAnyStrictV1 as AllowAnyStrict,
|
| 83 |
+
AllowAnyV1 as AllowAny,
|
| 84 |
+
AllowLazyStrictV1 as AllowLazyStrict,
|
| 85 |
+
AllowLazyV1 as AllowLazy,
|
| 86 |
+
AllowSeriesStrictV1 as AllowSeriesStrict,
|
| 87 |
+
AllowSeriesV1 as AllowSeries,
|
| 88 |
+
ExcludeSeriesStrictV1 as ExcludeSeriesStrict,
|
| 89 |
+
ExcludeSeriesV1 as ExcludeSeries,
|
| 90 |
+
IntoArrowTable,
|
| 91 |
+
OnlyEagerOrInterchange,
|
| 92 |
+
OnlyEagerOrInterchangeStrict,
|
| 93 |
+
OnlySeriesStrictV1 as OnlySeriesStrict,
|
| 94 |
+
OnlySeriesV1 as OnlySeries,
|
| 95 |
+
PassThroughUnknownV1 as PassThroughUnknown,
|
| 96 |
+
StrictUnknownV1 as StrictUnknown,
|
| 97 |
+
)
|
| 98 |
+
from narwhals._typing import (
|
| 99 |
+
Arrow,
|
| 100 |
+
Backend,
|
| 101 |
+
EagerAllowed,
|
| 102 |
+
IntoBackend,
|
| 103 |
+
LazyAllowed,
|
| 104 |
+
Pandas,
|
| 105 |
+
Polars,
|
| 106 |
+
)
|
| 107 |
+
from narwhals.dataframe import MultiColSelector, MultiIndexSelector
|
| 108 |
+
from narwhals.dtypes import DType
|
| 109 |
+
from narwhals.typing import (
|
| 110 |
+
FileSource,
|
| 111 |
+
IntoDType,
|
| 112 |
+
IntoExpr,
|
| 113 |
+
IntoSchema,
|
| 114 |
+
NonNestedLiteral,
|
| 115 |
+
PythonLiteral,
|
| 116 |
+
SingleColSelector,
|
| 117 |
+
SingleIndexSelector,
|
| 118 |
+
_1DArray,
|
| 119 |
+
_2DArray,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
T = TypeVar("T", default=Any)
|
| 123 |
+
P = ParamSpec("P")
|
| 124 |
+
R = TypeVar("R")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# NOTE legit
|
| 128 |
+
class DataFrame(NwDataFrame[IntoDataFrameT]): # type: ignore[type-var]
|
| 129 |
+
_version = Version.V1
|
| 130 |
+
|
| 131 |
+
@inherit_doc(NwDataFrame)
|
| 132 |
+
def __init__(self, df: Any, *, level: Literal["full", "lazy", "interchange"]) -> None:
|
| 133 |
+
assert df._version is Version.V1 # noqa: S101
|
| 134 |
+
super().__init__(df, level=level)
|
| 135 |
+
|
| 136 |
+
# We need to override any method which don't return Self so that type
|
| 137 |
+
# annotations are correct.
|
| 138 |
+
|
| 139 |
+
@classmethod
|
| 140 |
+
def from_arrow(
|
| 141 |
+
cls, native_frame: IntoArrowTable, *, backend: IntoBackend[EagerAllowed]
|
| 142 |
+
) -> DataFrame[Any]:
|
| 143 |
+
result = super().from_arrow(native_frame, backend=backend)
|
| 144 |
+
return cast("DataFrame[Any]", result)
|
| 145 |
+
|
| 146 |
+
@classmethod
|
| 147 |
+
def from_dict(
|
| 148 |
+
cls,
|
| 149 |
+
data: Mapping[str, Any],
|
| 150 |
+
schema: IntoSchema | Mapping[str, DType | None] | None = None,
|
| 151 |
+
*,
|
| 152 |
+
backend: IntoBackend[EagerAllowed] | None = None,
|
| 153 |
+
) -> DataFrame[Any]:
|
| 154 |
+
result = super().from_dict(data, schema, backend=backend)
|
| 155 |
+
return cast("DataFrame[Any]", result)
|
| 156 |
+
|
| 157 |
+
@classmethod
|
| 158 |
+
def from_dicts(
|
| 159 |
+
cls,
|
| 160 |
+
data: Sequence[Any],
|
| 161 |
+
schema: IntoSchema | Mapping[str, DType | None] | None = None,
|
| 162 |
+
*,
|
| 163 |
+
backend: IntoBackend[EagerAllowed],
|
| 164 |
+
) -> DataFrame[Any]:
|
| 165 |
+
result = super().from_dicts(data, schema, backend=backend)
|
| 166 |
+
return cast("DataFrame[Any]", result)
|
| 167 |
+
|
| 168 |
+
@classmethod
|
| 169 |
+
def from_numpy(
|
| 170 |
+
cls,
|
| 171 |
+
data: _2DArray,
|
| 172 |
+
schema: Mapping[str, DType] | Schema | Sequence[str] | None = None,
|
| 173 |
+
*,
|
| 174 |
+
backend: IntoBackend[EagerAllowed],
|
| 175 |
+
) -> DataFrame[Any]:
|
| 176 |
+
result = super().from_numpy(data, schema, backend=backend)
|
| 177 |
+
return cast("DataFrame[Any]", result)
|
| 178 |
+
|
| 179 |
+
@property
|
| 180 |
+
def _series(self) -> type[Series[Any]]:
|
| 181 |
+
return cast("type[Series[Any]]", Series)
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def _lazyframe(self) -> type[LazyFrame[Any]]:
|
| 185 |
+
return cast("type[LazyFrame[Any]]", LazyFrame)
|
| 186 |
+
|
| 187 |
+
@overload
|
| 188 |
+
def __getitem__(self, item: tuple[SingleIndexSelector, SingleColSelector]) -> Any: ...
|
| 189 |
+
|
| 190 |
+
@overload
|
| 191 |
+
def __getitem__( # type: ignore[overload-overlap]
|
| 192 |
+
self, item: str | tuple[MultiIndexSelector, SingleColSelector]
|
| 193 |
+
) -> Series[Any]: ...
|
| 194 |
+
|
| 195 |
+
@overload
|
| 196 |
+
def __getitem__(
|
| 197 |
+
self,
|
| 198 |
+
item: (
|
| 199 |
+
SingleIndexSelector
|
| 200 |
+
| MultiIndexSelector
|
| 201 |
+
| MultiColSelector
|
| 202 |
+
| tuple[SingleIndexSelector, MultiColSelector]
|
| 203 |
+
| tuple[MultiIndexSelector, MultiColSelector]
|
| 204 |
+
),
|
| 205 |
+
) -> Self: ...
|
| 206 |
+
def __getitem__(
|
| 207 |
+
self,
|
| 208 |
+
item: (
|
| 209 |
+
SingleIndexSelector
|
| 210 |
+
| SingleColSelector
|
| 211 |
+
| MultiColSelector
|
| 212 |
+
| MultiIndexSelector
|
| 213 |
+
| tuple[SingleIndexSelector, SingleColSelector]
|
| 214 |
+
| tuple[SingleIndexSelector, MultiColSelector]
|
| 215 |
+
| tuple[MultiIndexSelector, SingleColSelector]
|
| 216 |
+
| tuple[MultiIndexSelector, MultiColSelector]
|
| 217 |
+
),
|
| 218 |
+
) -> Series[Any] | Self | Any:
|
| 219 |
+
return super().__getitem__(item)
|
| 220 |
+
|
| 221 |
+
def get_column(self, name: str) -> Series:
|
| 222 |
+
# Type checkers complain that `nw.Series` is not assignable to `nw.v1.stable.Series`.
|
| 223 |
+
# However the return type actually is `nw.v1.stable.Series`, check `tests/v1_test.py`.
|
| 224 |
+
return super().get_column(name) # type: ignore[return-value]
|
| 225 |
+
|
| 226 |
+
def lazy(
|
| 227 |
+
self,
|
| 228 |
+
backend: IntoBackend[LazyAllowed] | None = None,
|
| 229 |
+
*,
|
| 230 |
+
session: Any | None = None,
|
| 231 |
+
) -> LazyFrame[Any]:
|
| 232 |
+
return _stableify(super().lazy(backend=backend, session=session))
|
| 233 |
+
|
| 234 |
+
@overload # type: ignore[override]
|
| 235 |
+
def to_dict(self, *, as_series: Literal[True] = ...) -> dict[str, Series[Any]]: ...
|
| 236 |
+
@overload
|
| 237 |
+
def to_dict(self, *, as_series: Literal[False]) -> dict[str, list[Any]]: ...
|
| 238 |
+
@overload
|
| 239 |
+
def to_dict(
|
| 240 |
+
self, *, as_series: bool = True
|
| 241 |
+
) -> dict[str, Series[Any]] | dict[str, list[Any]]: ...
|
| 242 |
+
def to_dict( # pyright: ignore[reportIncompatibleMethodOverride]
|
| 243 |
+
self, *, as_series: bool = True
|
| 244 |
+
) -> dict[str, Series[Any]] | dict[str, list[Any]]:
|
| 245 |
+
# Type checkers complain that `nw.Series` is not assignable to `nw.v1.stable.Series`.
|
| 246 |
+
# However the return type actually is `nw.v1.stable.Series`, check `tests/v1_test.py::test_to_dict_as_series`.
|
| 247 |
+
return super().to_dict(as_series=as_series) # type: ignore[return-value]
|
| 248 |
+
|
| 249 |
+
def is_duplicated(self) -> Series[Any]:
|
| 250 |
+
return _stableify(super().is_duplicated())
|
| 251 |
+
|
| 252 |
+
def is_unique(self) -> Series[Any]:
|
| 253 |
+
return _stableify(super().is_unique())
|
| 254 |
+
|
| 255 |
+
def _l1_norm(self) -> Self:
|
| 256 |
+
# Private, just used to test the stable API.
|
| 257 |
+
return self.select(all()._l1_norm())
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class LazyFrame(NwLazyFrame[IntoLazyFrameT]):
|
| 261 |
+
_version = Version.V1
|
| 262 |
+
|
| 263 |
+
@inherit_doc(NwLazyFrame)
|
| 264 |
+
def __init__(self, df: Any, *, level: Literal["full", "lazy", "interchange"]) -> None:
|
| 265 |
+
assert df._version is Version.V1 # noqa: S101
|
| 266 |
+
super().__init__(df, level=level)
|
| 267 |
+
|
| 268 |
+
@property
|
| 269 |
+
def _dataframe(self) -> type[DataFrame[Any]]:
|
| 270 |
+
return DataFrame
|
| 271 |
+
|
| 272 |
+
def _validate_metadata(self, metadata: ExprMetadata) -> None:
|
| 273 |
+
# After v1, we raise for order-dependent operations.
|
| 274 |
+
pass
|
| 275 |
+
|
| 276 |
+
def collect(
|
| 277 |
+
self, backend: IntoBackend[Polars | Pandas | Arrow] | None = None, **kwargs: Any
|
| 278 |
+
) -> DataFrame[Any]:
|
| 279 |
+
return _stableify(super().collect(backend=backend, **kwargs))
|
| 280 |
+
|
| 281 |
+
def _l1_norm(self) -> Self:
|
| 282 |
+
# Private, just used to test the stable API.
|
| 283 |
+
return self.select(all()._l1_norm())
|
| 284 |
+
|
| 285 |
+
def tail(self, n: int = 5) -> Self:
|
| 286 |
+
r"""Get the last `n` rows."""
|
| 287 |
+
return super().tail(n)
|
| 288 |
+
|
| 289 |
+
def gather_every(self, n: int, offset: int = 0) -> Self:
|
| 290 |
+
r"""Take every nth row in the DataFrame and return as a new DataFrame.
|
| 291 |
+
|
| 292 |
+
Arguments:
|
| 293 |
+
n: Gather every *n*-th row.
|
| 294 |
+
offset: Starting index.
|
| 295 |
+
"""
|
| 296 |
+
return self._with_compliant(
|
| 297 |
+
self._compliant_frame.gather_every(n=n, offset=offset) # type: ignore[attr-defined]
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
def with_row_index(
|
| 301 |
+
self, name: str = "index", *, order_by: str | Sequence[str] | None = None
|
| 302 |
+
) -> Self:
|
| 303 |
+
order_by_ = [order_by] if isinstance(order_by, str) else order_by
|
| 304 |
+
return self._with_compliant(
|
| 305 |
+
self._compliant_frame.with_row_index(
|
| 306 |
+
name=name,
|
| 307 |
+
order_by=order_by_, # type: ignore[arg-type]
|
| 308 |
+
)
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class Series(NwSeries[IntoSeriesT]):
|
| 313 |
+
_version = Version.V1
|
| 314 |
+
|
| 315 |
+
@inherit_doc(NwSeries)
|
| 316 |
+
def __init__(
|
| 317 |
+
self, series: Any, *, level: Literal["full", "lazy", "interchange"]
|
| 318 |
+
) -> None:
|
| 319 |
+
assert series._version is Version.V1 # noqa: S101
|
| 320 |
+
super().__init__(series, level=level)
|
| 321 |
+
|
| 322 |
+
# We need to override any method which don't return Self so that type
|
| 323 |
+
# annotations are correct.
|
| 324 |
+
|
| 325 |
+
@classmethod
|
| 326 |
+
def from_numpy(
|
| 327 |
+
cls,
|
| 328 |
+
name: str,
|
| 329 |
+
values: _1DArray,
|
| 330 |
+
dtype: IntoDType | None = None,
|
| 331 |
+
*,
|
| 332 |
+
backend: IntoBackend[EagerAllowed],
|
| 333 |
+
) -> Series[Any]:
|
| 334 |
+
result = super().from_numpy(name, values, dtype, backend=backend)
|
| 335 |
+
return cast("Series[Any]", result)
|
| 336 |
+
|
| 337 |
+
@classmethod
|
| 338 |
+
def from_iterable(
|
| 339 |
+
cls,
|
| 340 |
+
name: str,
|
| 341 |
+
values: Iterable[Any],
|
| 342 |
+
dtype: IntoDType | None = None,
|
| 343 |
+
*,
|
| 344 |
+
backend: IntoBackend[EagerAllowed],
|
| 345 |
+
) -> Series[Any]:
|
| 346 |
+
result = super().from_iterable(name, values, dtype, backend=backend)
|
| 347 |
+
return cast("Series[Any]", result)
|
| 348 |
+
|
| 349 |
+
@property
|
| 350 |
+
def _dataframe(self) -> type[DataFrame[Any]]:
|
| 351 |
+
return DataFrame
|
| 352 |
+
|
| 353 |
+
def to_frame(self) -> DataFrame[Any]:
|
| 354 |
+
return _stableify(super().to_frame())
|
| 355 |
+
|
| 356 |
+
def value_counts(
|
| 357 |
+
self,
|
| 358 |
+
*,
|
| 359 |
+
sort: bool = False,
|
| 360 |
+
parallel: bool = False,
|
| 361 |
+
name: str | None = None,
|
| 362 |
+
normalize: bool = False,
|
| 363 |
+
) -> DataFrame[Any]:
|
| 364 |
+
return _stableify(
|
| 365 |
+
super().value_counts(
|
| 366 |
+
sort=sort, parallel=parallel, name=name, normalize=normalize
|
| 367 |
+
)
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
def hist(
|
| 371 |
+
self,
|
| 372 |
+
bins: list[float] | None = None,
|
| 373 |
+
*,
|
| 374 |
+
bin_count: int | None = None,
|
| 375 |
+
include_breakpoint: bool = True,
|
| 376 |
+
) -> DataFrame[Any]:
|
| 377 |
+
msg = (
|
| 378 |
+
"`Series.hist` is being called from the stable API although considered "
|
| 379 |
+
"an unstable feature."
|
| 380 |
+
)
|
| 381 |
+
issue_warning(msg, NarwhalsUnstableWarning)
|
| 382 |
+
return _stableify(
|
| 383 |
+
super().hist(
|
| 384 |
+
bins=bins, bin_count=bin_count, include_breakpoint=include_breakpoint
|
| 385 |
+
)
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
def any_value(self, *, ignore_nulls: bool = False) -> PythonLiteral:
|
| 389 |
+
msg = (
|
| 390 |
+
"`Series.any_value` is being called from the stable API although considered "
|
| 391 |
+
"an unstable feature."
|
| 392 |
+
)
|
| 393 |
+
issue_warning(msg, NarwhalsUnstableWarning)
|
| 394 |
+
return super().any_value(ignore_nulls=ignore_nulls)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
class Expr(NwExpr):
|
| 398 |
+
def _l1_norm(self) -> Self:
|
| 399 |
+
return super()._taxicab_norm()
|
| 400 |
+
|
| 401 |
+
def head(self, n: int = 10) -> Self:
|
| 402 |
+
r"""Get the first `n` rows."""
|
| 403 |
+
return self._append_node(ExprNode(ExprKind.ORDERABLE_FILTRATION, "head", n=n))
|
| 404 |
+
|
| 405 |
+
def tail(self, n: int = 10) -> Self:
|
| 406 |
+
r"""Get the last `n` rows."""
|
| 407 |
+
return self._append_node(ExprNode(ExprKind.ORDERABLE_FILTRATION, "tail", n=n))
|
| 408 |
+
|
| 409 |
+
def gather_every(self, n: int, offset: int = 0) -> Self:
|
| 410 |
+
r"""Take every nth value in the Series and return as new Series.
|
| 411 |
+
|
| 412 |
+
Arguments:
|
| 413 |
+
n: Gather every *n*-th row.
|
| 414 |
+
offset: Starting index.
|
| 415 |
+
"""
|
| 416 |
+
return self._append_node(
|
| 417 |
+
ExprNode(ExprKind.ORDERABLE_FILTRATION, "gather_every", n=n, offset=offset)
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
def unique(self, *, maintain_order: bool | None = None) -> Self:
|
| 421 |
+
"""Return unique values of this expression."""
|
| 422 |
+
if maintain_order is not None:
|
| 423 |
+
msg = (
|
| 424 |
+
"`maintain_order` has no effect and is only kept around for backwards-compatibility. "
|
| 425 |
+
"You can safely remove this argument."
|
| 426 |
+
)
|
| 427 |
+
issue_warning(msg, UserWarning)
|
| 428 |
+
return self._append_node(ExprNode(ExprKind.FILTRATION, "unique"))
|
| 429 |
+
|
| 430 |
+
def sort(self, *, descending: bool = False, nulls_last: bool = False) -> Self:
|
| 431 |
+
"""Sort this column. Place null values first."""
|
| 432 |
+
return self._append_node(
|
| 433 |
+
ExprNode(
|
| 434 |
+
ExprKind.WINDOW, "sort", descending=descending, nulls_last=nulls_last
|
| 435 |
+
)
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
def arg_max(self) -> Self:
|
| 439 |
+
"""Returns the index of the maximum value."""
|
| 440 |
+
return self._append_node(ExprNode(ExprKind.ORDERABLE_AGGREGATION, "arg_max"))
|
| 441 |
+
|
| 442 |
+
def arg_min(self) -> Self:
|
| 443 |
+
"""Returns the index of the minimum value."""
|
| 444 |
+
return self._append_node(ExprNode(ExprKind.ORDERABLE_AGGREGATION, "arg_min"))
|
| 445 |
+
|
| 446 |
+
def arg_true(self) -> Self:
|
| 447 |
+
"""Find elements where boolean expression is True."""
|
| 448 |
+
return self._append_node(ExprNode(ExprKind.ORDERABLE_FILTRATION, "arg_true"))
|
| 449 |
+
|
| 450 |
+
def first(self) -> Self: # type: ignore[override]
|
| 451 |
+
"""Get the first value."""
|
| 452 |
+
return self._append_node(ExprNode(ExprKind.ORDERABLE_AGGREGATION, "first"))
|
| 453 |
+
|
| 454 |
+
def last(self) -> Self: # type: ignore[override]
|
| 455 |
+
"""Get the last value."""
|
| 456 |
+
return self._append_node(ExprNode(ExprKind.ORDERABLE_AGGREGATION, "last"))
|
| 457 |
+
|
| 458 |
+
def sample(
|
| 459 |
+
self,
|
| 460 |
+
n: int | None = None,
|
| 461 |
+
*,
|
| 462 |
+
fraction: float | None = None,
|
| 463 |
+
with_replacement: bool = False,
|
| 464 |
+
seed: int | None = None,
|
| 465 |
+
) -> Self:
|
| 466 |
+
"""Sample randomly from this expression.
|
| 467 |
+
|
| 468 |
+
Arguments:
|
| 469 |
+
n: Number of items to return. Cannot be used with fraction.
|
| 470 |
+
fraction: Fraction of items to return. Cannot be used with n.
|
| 471 |
+
with_replacement: Allow values to be sampled more than once.
|
| 472 |
+
seed: Seed for the random number generator. If set to None (default), a random
|
| 473 |
+
seed is generated for each sample operation.
|
| 474 |
+
"""
|
| 475 |
+
return self._append_node(
|
| 476 |
+
ExprNode(
|
| 477 |
+
ExprKind.FILTRATION,
|
| 478 |
+
"sample",
|
| 479 |
+
n=n,
|
| 480 |
+
fraction=fraction,
|
| 481 |
+
with_replacement=with_replacement,
|
| 482 |
+
seed=seed,
|
| 483 |
+
)
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
def any_value(self, *, ignore_nulls: bool = False) -> Self:
|
| 487 |
+
msg = (
|
| 488 |
+
"`Expr.any_value` is being called from the stable API although considered "
|
| 489 |
+
"an unstable feature."
|
| 490 |
+
)
|
| 491 |
+
issue_warning(msg, NarwhalsUnstableWarning)
|
| 492 |
+
return self._append_node(
|
| 493 |
+
ExprNode(ExprKind.AGGREGATION, "any_value", ignore_nulls=ignore_nulls)
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
class Schema(NwSchema):
|
| 498 |
+
_version = Version.V1
|
| 499 |
+
|
| 500 |
+
@inherit_doc(NwSchema)
|
| 501 |
+
def __init__(
|
| 502 |
+
self, schema: Mapping[str, DType] | Iterable[tuple[str, DType]] | None = None
|
| 503 |
+
) -> None:
|
| 504 |
+
super().__init__(schema)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
@overload
|
| 508 |
+
def _stableify(obj: NwDataFrame[IntoDataFrameT]) -> DataFrame[IntoDataFrameT]: ... # type: ignore[type-var]
|
| 509 |
+
@overload
|
| 510 |
+
def _stableify(obj: NwLazyFrame[IntoLazyFrameT]) -> LazyFrame[IntoLazyFrameT]: ...
|
| 511 |
+
@overload
|
| 512 |
+
def _stableify(obj: NwSeries[IntoSeriesT]) -> Series[IntoSeriesT]: ...
|
| 513 |
+
@overload
|
| 514 |
+
def _stableify(obj: NwExpr) -> Expr: ...
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def _stableify(
|
| 518 |
+
obj: NwDataFrame[IntoDataFrameT] # type: ignore[type-var]
|
| 519 |
+
| NwLazyFrame[IntoLazyFrameT]
|
| 520 |
+
| NwSeries[IntoSeriesT]
|
| 521 |
+
| NwExpr,
|
| 522 |
+
) -> DataFrame[IntoDataFrameT] | LazyFrame[IntoLazyFrameT] | Series[IntoSeriesT] | Expr:
|
| 523 |
+
if isinstance(obj, NwDataFrame):
|
| 524 |
+
return DataFrame(obj._compliant_frame._with_version(Version.V1), level=obj._level)
|
| 525 |
+
if isinstance(obj, NwLazyFrame):
|
| 526 |
+
return LazyFrame(obj._compliant_frame._with_version(Version.V1), level=obj._level)
|
| 527 |
+
if isinstance(obj, NwSeries):
|
| 528 |
+
return Series(obj._compliant_series._with_version(Version.V1), level=obj._level)
|
| 529 |
+
if isinstance(obj, NwExpr):
|
| 530 |
+
return Expr(*obj._nodes)
|
| 531 |
+
assert_never(obj)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
@overload
|
| 535 |
+
def from_native(native_object: SeriesT, **kwds: Unpack[OnlySeries]) -> SeriesT: ...
|
| 536 |
+
@overload
|
| 537 |
+
def from_native(native_object: SeriesT, **kwds: Unpack[OnlySeriesStrict]) -> SeriesT: ...
|
| 538 |
+
@overload
|
| 539 |
+
def from_native(native_object: SeriesT, **kwds: Unpack[AllowSeries]) -> SeriesT: ...
|
| 540 |
+
@overload
|
| 541 |
+
def from_native(native_object: SeriesT, **kwds: Unpack[AllowSeriesStrict]) -> SeriesT: ...
|
| 542 |
+
@overload
|
| 543 |
+
def from_native(
|
| 544 |
+
native_object: DataFrameT, **kwds: Unpack[ExcludeSeries]
|
| 545 |
+
) -> DataFrameT: ...
|
| 546 |
+
@overload
|
| 547 |
+
def from_native(
|
| 548 |
+
native_object: DataFrameT, **kwds: Unpack[ExcludeSeriesStrict]
|
| 549 |
+
) -> DataFrameT: ...
|
| 550 |
+
@overload
|
| 551 |
+
def from_native(native_object: LazyFrameT, **kwds: Unpack[AllowLazy]) -> LazyFrameT: ...
|
| 552 |
+
@overload
|
| 553 |
+
def from_native(
|
| 554 |
+
native_object: LazyFrameT, **kwds: Unpack[AllowLazyStrict]
|
| 555 |
+
) -> LazyFrameT: ...
|
| 556 |
+
@overload
|
| 557 |
+
def from_native(
|
| 558 |
+
native_object: IntoDataFrameT, **kwds: Unpack[OnlyEagerOrInterchange]
|
| 559 |
+
) -> DataFrame[IntoDataFrameT]: ...
|
| 560 |
+
@overload
|
| 561 |
+
def from_native(
|
| 562 |
+
native_object: IntoDataFrameT, **kwds: Unpack[OnlyEagerOrInterchangeStrict]
|
| 563 |
+
) -> DataFrame[IntoDataFrameT]: ...
|
| 564 |
+
@overload
|
| 565 |
+
def from_native(
|
| 566 |
+
native_object: IntoDataFrameT, **kwds: Unpack[ExcludeSeries]
|
| 567 |
+
) -> DataFrame[IntoDataFrameT]: ...
|
| 568 |
+
@overload
|
| 569 |
+
def from_native(
|
| 570 |
+
native_object: IntoDataFrameT, **kwds: Unpack[ExcludeSeriesStrict]
|
| 571 |
+
) -> DataFrame[IntoDataFrameT]: ...
|
| 572 |
+
@overload
|
| 573 |
+
def from_native(
|
| 574 |
+
native_object: IntoSeriesT, **kwds: Unpack[OnlySeries]
|
| 575 |
+
) -> Series[IntoSeriesT]: ...
|
| 576 |
+
@overload
|
| 577 |
+
def from_native(
|
| 578 |
+
native_object: IntoSeriesT, **kwds: Unpack[OnlySeriesStrict]
|
| 579 |
+
) -> Series[IntoSeriesT]: ...
|
| 580 |
+
@overload
|
| 581 |
+
def from_native(
|
| 582 |
+
native_object: IntoDataFrameT | IntoSeriesT, **kwds: Unpack[AllowSeries]
|
| 583 |
+
) -> DataFrame[IntoDataFrameT] | Series[IntoSeriesT]: ...
|
| 584 |
+
@overload
|
| 585 |
+
def from_native(
|
| 586 |
+
native_object: IntoDataFrameT | IntoSeriesT, **kwds: Unpack[AllowSeriesStrict]
|
| 587 |
+
) -> DataFrame[IntoDataFrameT] | Series[IntoSeriesT]: ...
|
| 588 |
+
@overload
|
| 589 |
+
def from_native(
|
| 590 |
+
native_object: IntoLazyFrameT, **kwds: Unpack[AllowLazy]
|
| 591 |
+
) -> LazyFrame[IntoLazyFrameT]: ...
|
| 592 |
+
@overload
|
| 593 |
+
def from_native(
|
| 594 |
+
native_object: IntoLazyFrameT, **kwds: Unpack[AllowLazyStrict]
|
| 595 |
+
) -> LazyFrame[IntoLazyFrameT]: ...
|
| 596 |
+
@overload
|
| 597 |
+
def from_native(
|
| 598 |
+
native_object: IntoDataFrameT | IntoLazyFrameT | IntoSeriesT, **kwds: Unpack[AllowAny]
|
| 599 |
+
) -> DataFrame[IntoDataFrameT] | LazyFrame[IntoLazyFrameT] | Series[IntoSeriesT]: ...
|
| 600 |
+
@overload
|
| 601 |
+
def from_native(
|
| 602 |
+
native_object: IntoDataFrameT | IntoLazyFrameT | IntoSeriesT,
|
| 603 |
+
**kwds: Unpack[AllowAnyStrict],
|
| 604 |
+
) -> DataFrame[IntoDataFrameT] | LazyFrame[IntoLazyFrameT] | Series[IntoSeriesT]: ...
|
| 605 |
+
@overload
|
| 606 |
+
def from_native(native_object: T, **kwds: Unpack[PassThroughUnknown]) -> T: ...
|
| 607 |
+
@overload
|
| 608 |
+
def from_native(native_object: T, **kwds: Unpack[StrictUnknown]) -> T: ...
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
# All params passed in as variables
|
| 612 |
+
@overload
|
| 613 |
+
def from_native(
|
| 614 |
+
native_object: Any,
|
| 615 |
+
*,
|
| 616 |
+
pass_through: bool,
|
| 617 |
+
eager_only: bool,
|
| 618 |
+
eager_or_interchange_only: bool = False,
|
| 619 |
+
series_only: bool,
|
| 620 |
+
allow_series: bool | None,
|
| 621 |
+
) -> Any: ...
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def from_native(
|
| 625 |
+
native_object: IntoDataFrameT
|
| 626 |
+
| IntoLazyFrameT
|
| 627 |
+
| IntoFrame
|
| 628 |
+
| IntoSeriesT
|
| 629 |
+
| IntoSeries
|
| 630 |
+
| T,
|
| 631 |
+
*,
|
| 632 |
+
strict: bool | None = None,
|
| 633 |
+
pass_through: bool | None = None,
|
| 634 |
+
eager_only: bool = False,
|
| 635 |
+
eager_or_interchange_only: bool = False,
|
| 636 |
+
series_only: bool = False,
|
| 637 |
+
allow_series: bool | None = None,
|
| 638 |
+
**kwds: Any,
|
| 639 |
+
) -> LazyFrame[IntoLazyFrameT] | DataFrame[IntoDataFrameT] | Series[IntoSeriesT] | T:
|
| 640 |
+
"""Convert `native_object` to Narwhals Dataframe, Lazyframe, or Series.
|
| 641 |
+
|
| 642 |
+
See `narwhals.from_native` for full docstring. Note that `native_namespace` is
|
| 643 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 644 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 645 |
+
"""
|
| 646 |
+
# Early returns
|
| 647 |
+
if isinstance(native_object, (DataFrame, LazyFrame)) and not series_only:
|
| 648 |
+
return native_object
|
| 649 |
+
if isinstance(native_object, Series) and (series_only or allow_series):
|
| 650 |
+
return native_object
|
| 651 |
+
|
| 652 |
+
pass_through = validate_strict_and_pass_though(
|
| 653 |
+
strict, pass_through, pass_through_default=False
|
| 654 |
+
)
|
| 655 |
+
if kwds:
|
| 656 |
+
msg = f"from_native() got an unexpected keyword argument {next(iter(kwds))!r}"
|
| 657 |
+
raise TypeError(msg)
|
| 658 |
+
|
| 659 |
+
return _from_native_impl( # type: ignore[no-any-return]
|
| 660 |
+
native_object,
|
| 661 |
+
pass_through=pass_through,
|
| 662 |
+
eager_only=eager_only,
|
| 663 |
+
eager_or_interchange_only=eager_or_interchange_only,
|
| 664 |
+
series_only=series_only,
|
| 665 |
+
allow_series=allow_series,
|
| 666 |
+
version=Version.V1,
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
@overload
|
| 671 |
+
def to_native(
|
| 672 |
+
narwhals_object: DataFrame[IntoDataFrameT], *, strict: Literal[True] = ...
|
| 673 |
+
) -> IntoDataFrameT: ...
|
| 674 |
+
@overload
|
| 675 |
+
def to_native(
|
| 676 |
+
narwhals_object: LazyFrame[IntoLazyFrameT], *, strict: Literal[True] = ...
|
| 677 |
+
) -> IntoLazyFrameT: ...
|
| 678 |
+
@overload
|
| 679 |
+
def to_native(
|
| 680 |
+
narwhals_object: Series[IntoSeriesT], *, strict: Literal[True] = ...
|
| 681 |
+
) -> IntoSeriesT: ...
|
| 682 |
+
@overload
|
| 683 |
+
def to_native(narwhals_object: Any, *, strict: bool) -> Any: ...
|
| 684 |
+
@overload
|
| 685 |
+
def to_native(
|
| 686 |
+
narwhals_object: DataFrame[IntoDataFrameT], *, pass_through: Literal[False] = ...
|
| 687 |
+
) -> IntoDataFrameT: ...
|
| 688 |
+
@overload
|
| 689 |
+
def to_native(
|
| 690 |
+
narwhals_object: LazyFrame[IntoLazyFrameT], *, pass_through: Literal[False] = ...
|
| 691 |
+
) -> IntoLazyFrameT: ...
|
| 692 |
+
@overload
|
| 693 |
+
def to_native(
|
| 694 |
+
narwhals_object: Series[IntoSeriesT], *, pass_through: Literal[False] = ...
|
| 695 |
+
) -> IntoSeriesT: ...
|
| 696 |
+
@overload
|
| 697 |
+
def to_native(narwhals_object: Any, *, pass_through: bool) -> Any: ...
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
def to_native(
|
| 701 |
+
narwhals_object: DataFrame[IntoDataFrameT]
|
| 702 |
+
| LazyFrame[IntoLazyFrameT]
|
| 703 |
+
| Series[IntoSeriesT],
|
| 704 |
+
*,
|
| 705 |
+
strict: bool | None = None,
|
| 706 |
+
pass_through: bool | None = None,
|
| 707 |
+
) -> IntoLazyFrameT | IntoDataFrameT | IntoSeriesT | Any:
|
| 708 |
+
"""Convert Narwhals object to native one.
|
| 709 |
+
|
| 710 |
+
See `narwhals.to_native` for full docstring. Note that `native_namespace` is
|
| 711 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 712 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 713 |
+
"""
|
| 714 |
+
from narwhals._utils import validate_strict_and_pass_though
|
| 715 |
+
|
| 716 |
+
pass_through = validate_strict_and_pass_though(
|
| 717 |
+
strict, pass_through, pass_through_default=False
|
| 718 |
+
)
|
| 719 |
+
return nw.to_native(narwhals_object, pass_through=pass_through)
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
def narwhalify(
|
| 723 |
+
func: Callable[..., Any] | None = None,
|
| 724 |
+
*,
|
| 725 |
+
strict: bool | None = None,
|
| 726 |
+
pass_through: bool | None = None,
|
| 727 |
+
eager_only: bool = False,
|
| 728 |
+
eager_or_interchange_only: bool = False,
|
| 729 |
+
series_only: bool = False,
|
| 730 |
+
allow_series: bool | None = True,
|
| 731 |
+
) -> Callable[..., Any]:
|
| 732 |
+
"""Decorate function so it becomes dataframe-agnostic.
|
| 733 |
+
|
| 734 |
+
See `narwhals.narwhalify` for full docstring. Note that `native_namespace` is
|
| 735 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 736 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 737 |
+
"""
|
| 738 |
+
pass_through = validate_strict_and_pass_though(
|
| 739 |
+
strict, pass_through, pass_through_default=True
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
| 743 |
+
@wraps(func)
|
| 744 |
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
| 745 |
+
args_nw = [
|
| 746 |
+
from_native(
|
| 747 |
+
arg,
|
| 748 |
+
pass_through=pass_through,
|
| 749 |
+
eager_only=eager_only,
|
| 750 |
+
eager_or_interchange_only=eager_or_interchange_only,
|
| 751 |
+
series_only=series_only,
|
| 752 |
+
allow_series=allow_series,
|
| 753 |
+
)
|
| 754 |
+
for arg in args
|
| 755 |
+
]
|
| 756 |
+
|
| 757 |
+
kwargs_nw = {
|
| 758 |
+
name: from_native(
|
| 759 |
+
value,
|
| 760 |
+
pass_through=pass_through,
|
| 761 |
+
eager_only=eager_only,
|
| 762 |
+
eager_or_interchange_only=eager_or_interchange_only,
|
| 763 |
+
series_only=series_only,
|
| 764 |
+
allow_series=allow_series,
|
| 765 |
+
)
|
| 766 |
+
for name, value in kwargs.items()
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
backends = {
|
| 770 |
+
b()
|
| 771 |
+
for v in (*args_nw, *kwargs_nw.values())
|
| 772 |
+
if (b := getattr(v, "__native_namespace__", None))
|
| 773 |
+
}
|
| 774 |
+
|
| 775 |
+
if backends.__len__() > 1:
|
| 776 |
+
msg = "Found multiple backends. Make sure that all dataframe/series inputs come from the same backend."
|
| 777 |
+
raise ValueError(msg)
|
| 778 |
+
|
| 779 |
+
result = func(*args_nw, **kwargs_nw)
|
| 780 |
+
|
| 781 |
+
return to_native(result, pass_through=pass_through)
|
| 782 |
+
|
| 783 |
+
return wrapper
|
| 784 |
+
|
| 785 |
+
if func is None:
|
| 786 |
+
return decorator
|
| 787 |
+
# If func is not None, it means the decorator is used without arguments
|
| 788 |
+
return decorator(func)
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def all() -> Expr:
|
| 792 |
+
return _stableify(nw.all())
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def col(*names: str | Iterable[str]) -> Expr:
|
| 796 |
+
return _stableify(nw.col(*names))
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
def exclude(*names: str | Iterable[str]) -> Expr:
|
| 800 |
+
return _stableify(nw.exclude(*names))
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def nth(*indices: int | Sequence[int]) -> Expr:
|
| 804 |
+
return _stableify(nw.nth(*indices))
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def len() -> Expr:
|
| 808 |
+
return _stableify(nw.len())
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def lit(value: NonNestedLiteral, dtype: IntoDType | None = None) -> Expr:
|
| 812 |
+
return _stableify(nw.lit(value, dtype))
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def min(*columns: str) -> Expr:
|
| 816 |
+
return _stableify(nw.min(*columns))
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
def max(*columns: str) -> Expr:
|
| 820 |
+
return _stableify(nw.max(*columns))
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
def mean(*columns: str) -> Expr:
|
| 824 |
+
return _stableify(nw.mean(*columns))
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
def median(*columns: str) -> Expr:
|
| 828 |
+
return _stableify(nw.median(*columns))
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
def sum(*columns: str) -> Expr:
|
| 832 |
+
return _stableify(nw.sum(*columns))
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def sum_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr:
|
| 836 |
+
return _stableify(nw.sum_horizontal(*exprs))
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
def all_horizontal(
|
| 840 |
+
*exprs: IntoExpr | Iterable[IntoExpr], ignore_nulls: bool = False
|
| 841 |
+
) -> Expr:
|
| 842 |
+
return _stableify(nw.all_horizontal(*exprs, ignore_nulls=ignore_nulls))
|
| 843 |
+
|
| 844 |
+
|
| 845 |
+
def any_horizontal(
|
| 846 |
+
*exprs: IntoExpr | Iterable[IntoExpr], ignore_nulls: bool = False
|
| 847 |
+
) -> Expr:
|
| 848 |
+
return _stableify(nw.any_horizontal(*exprs, ignore_nulls=ignore_nulls))
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def mean_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr:
|
| 852 |
+
return _stableify(nw.mean_horizontal(*exprs))
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def min_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr:
|
| 856 |
+
return _stableify(nw.min_horizontal(*exprs))
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def max_horizontal(*exprs: IntoExpr | Iterable[IntoExpr]) -> Expr:
|
| 860 |
+
return _stableify(nw.max_horizontal(*exprs))
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
def concat_str(
|
| 864 |
+
exprs: IntoExpr | Iterable[IntoExpr],
|
| 865 |
+
*more_exprs: IntoExpr,
|
| 866 |
+
separator: str = "",
|
| 867 |
+
ignore_nulls: bool = False,
|
| 868 |
+
) -> Expr:
|
| 869 |
+
return _stableify(
|
| 870 |
+
nw.concat_str(exprs, *more_exprs, separator=separator, ignore_nulls=ignore_nulls)
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
|
| 874 |
+
def format(f_string: str, *args: IntoExpr) -> Expr:
|
| 875 |
+
"""Format expressions as a string."""
|
| 876 |
+
return _stableify(nw.format(f_string, *args))
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
def coalesce(exprs: IntoExpr | Iterable[IntoExpr], *more_exprs: IntoExpr) -> Expr:
|
| 880 |
+
return _stableify(nw.coalesce(exprs, *more_exprs))
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def get_level(
|
| 884 |
+
obj: DataFrame[Any] | LazyFrame[Any] | Series[IntoSeriesT],
|
| 885 |
+
) -> Literal["full", "lazy", "interchange"]:
|
| 886 |
+
"""Level of support Narwhals has for current object.
|
| 887 |
+
|
| 888 |
+
Arguments:
|
| 889 |
+
obj: Dataframe or Series.
|
| 890 |
+
|
| 891 |
+
Returns:
|
| 892 |
+
This can be one of
|
| 893 |
+
|
| 894 |
+
- 'full': full Narwhals API support
|
| 895 |
+
- 'lazy': only lazy operations are supported. This excludes anything
|
| 896 |
+
which involves iterating over rows in Python.
|
| 897 |
+
- 'interchange': only metadata operations are supported (`df.schema`)
|
| 898 |
+
"""
|
| 899 |
+
return obj._level
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
class When(nw_f.When):
|
| 903 |
+
@classmethod
|
| 904 |
+
def from_when(cls, when: nw_f.When) -> When:
|
| 905 |
+
return cls(when._predicate)
|
| 906 |
+
|
| 907 |
+
def then(self, value: IntoExpr | NonNestedLiteral | _1DArray) -> Then:
|
| 908 |
+
return Then.from_then(super().then(value))
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
class Then(nw_f.Then, Expr):
|
| 912 |
+
@classmethod
|
| 913 |
+
def from_then(cls, then: nw_f.Then) -> Then:
|
| 914 |
+
return cls(*then._nodes)
|
| 915 |
+
|
| 916 |
+
def otherwise(self, value: IntoExpr | NonNestedLiteral | _1DArray) -> Expr:
|
| 917 |
+
return _stableify(super().otherwise(value))
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def when(*predicates: IntoExpr | Iterable[IntoExpr]) -> When:
|
| 921 |
+
return When.from_when(nw_f.when(*predicates))
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
@deprecate_native_namespace(required=True)
|
| 925 |
+
def new_series(
|
| 926 |
+
name: str,
|
| 927 |
+
values: Any,
|
| 928 |
+
dtype: IntoDType | None = None,
|
| 929 |
+
*,
|
| 930 |
+
backend: IntoBackend[EagerAllowed] | None = None,
|
| 931 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 932 |
+
) -> Series[Any]:
|
| 933 |
+
"""Instantiate Narwhals Series from iterable (e.g. list or array).
|
| 934 |
+
|
| 935 |
+
See `narwhals.new_series` for full docstring. Note that `native_namespace` is
|
| 936 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 937 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 938 |
+
"""
|
| 939 |
+
backend = cast("IntoBackend[EagerAllowed]", backend)
|
| 940 |
+
return _stableify(_new_series_impl(name, values, dtype, backend=backend))
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
@deprecate_native_namespace(required=True)
|
| 944 |
+
def from_arrow(
|
| 945 |
+
native_frame: IntoArrowTable,
|
| 946 |
+
*,
|
| 947 |
+
backend: IntoBackend[EagerAllowed] | None = None,
|
| 948 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 949 |
+
) -> DataFrame[Any]:
|
| 950 |
+
"""Construct a DataFrame from an object which supports the PyCapsule Interface.
|
| 951 |
+
|
| 952 |
+
See `narwhals.from_arrow` for full docstring. Note that `native_namespace` is
|
| 953 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 954 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 955 |
+
"""
|
| 956 |
+
backend = cast("IntoBackend[EagerAllowed]", backend)
|
| 957 |
+
return _stableify(nw_f.from_arrow(native_frame, backend=backend))
|
| 958 |
+
|
| 959 |
+
|
| 960 |
+
@deprecate_native_namespace()
|
| 961 |
+
def from_dict(
|
| 962 |
+
data: Mapping[str, Any],
|
| 963 |
+
schema: Mapping[str, DType] | Schema | None = None,
|
| 964 |
+
*,
|
| 965 |
+
backend: IntoBackend[EagerAllowed] | None = None,
|
| 966 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 967 |
+
) -> DataFrame[Any]:
|
| 968 |
+
"""Instantiate DataFrame from dictionary.
|
| 969 |
+
|
| 970 |
+
See `narwhals.from_dict` for full docstring. Note that `native_namespace` is
|
| 971 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 972 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 973 |
+
"""
|
| 974 |
+
return _stableify(nw_f.from_dict(data, schema, backend=backend))
|
| 975 |
+
|
| 976 |
+
|
| 977 |
+
from_dicts: Final = DataFrame.from_dicts
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
@deprecate_native_namespace(required=True)
|
| 981 |
+
def from_numpy(
|
| 982 |
+
data: _2DArray,
|
| 983 |
+
schema: Mapping[str, DType] | Schema | Sequence[str] | None = None,
|
| 984 |
+
*,
|
| 985 |
+
backend: IntoBackend[EagerAllowed] | None = None,
|
| 986 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 987 |
+
) -> DataFrame[Any]:
|
| 988 |
+
"""Construct a DataFrame from a NumPy ndarray.
|
| 989 |
+
|
| 990 |
+
See `narwhals.from_numpy` for full docstring. Note that `native_namespace` is
|
| 991 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 992 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 993 |
+
"""
|
| 994 |
+
backend = cast("IntoBackend[EagerAllowed]", backend)
|
| 995 |
+
return _stableify(nw_f.from_numpy(data, schema, backend=backend))
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
@deprecate_native_namespace(required=True)
|
| 999 |
+
def read_csv(
|
| 1000 |
+
source: FileSource,
|
| 1001 |
+
*,
|
| 1002 |
+
backend: IntoBackend[EagerAllowed] | None = None,
|
| 1003 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 1004 |
+
**kwargs: Any,
|
| 1005 |
+
) -> DataFrame[Any]:
|
| 1006 |
+
"""Read a CSV file into a DataFrame.
|
| 1007 |
+
|
| 1008 |
+
See `narwhals.read_csv` for full docstring. Note that `native_namespace` is
|
| 1009 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 1010 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 1011 |
+
"""
|
| 1012 |
+
backend = cast("IntoBackend[EagerAllowed]", backend)
|
| 1013 |
+
return _stableify(nw_f.read_csv(source, backend=backend, **kwargs))
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
@deprecate_native_namespace(required=True)
|
| 1017 |
+
def scan_csv(
|
| 1018 |
+
source: FileSource,
|
| 1019 |
+
*,
|
| 1020 |
+
backend: IntoBackend[Backend] | None = None,
|
| 1021 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 1022 |
+
**kwargs: Any,
|
| 1023 |
+
) -> LazyFrame[Any]:
|
| 1024 |
+
"""Lazily read from a CSV file.
|
| 1025 |
+
|
| 1026 |
+
See `narwhals.scan_csv` for full docstring. Note that `native_namespace` is
|
| 1027 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 1028 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 1029 |
+
"""
|
| 1030 |
+
backend = cast("IntoBackend[Backend]", backend)
|
| 1031 |
+
return _stableify(nw_f.scan_csv(source, backend=backend, **kwargs))
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
@deprecate_native_namespace(required=True)
|
| 1035 |
+
def read_parquet(
|
| 1036 |
+
source: FileSource,
|
| 1037 |
+
*,
|
| 1038 |
+
backend: IntoBackend[EagerAllowed] | None = None,
|
| 1039 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 1040 |
+
**kwargs: Any,
|
| 1041 |
+
) -> DataFrame[Any]:
|
| 1042 |
+
"""Read into a DataFrame from a parquet file.
|
| 1043 |
+
|
| 1044 |
+
See `narwhals.read_parquet` for full docstring. Note that `native_namespace` is
|
| 1045 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 1046 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 1047 |
+
"""
|
| 1048 |
+
backend = cast("IntoBackend[EagerAllowed]", backend)
|
| 1049 |
+
return _stableify(nw_f.read_parquet(source, backend=backend, **kwargs))
|
| 1050 |
+
|
| 1051 |
+
|
| 1052 |
+
@deprecate_native_namespace(required=True)
|
| 1053 |
+
def scan_parquet(
|
| 1054 |
+
source: FileSource,
|
| 1055 |
+
*,
|
| 1056 |
+
backend: IntoBackend[Backend] | None = None,
|
| 1057 |
+
native_namespace: ModuleType | None = None, # noqa: ARG001
|
| 1058 |
+
**kwargs: Any,
|
| 1059 |
+
) -> LazyFrame[Any]:
|
| 1060 |
+
"""Lazily read from a parquet file.
|
| 1061 |
+
|
| 1062 |
+
See `narwhals.scan_parquet` for full docstring. Note that `native_namespace` is
|
| 1063 |
+
an is the same as `backend` but only accepts module types - for new code, we
|
| 1064 |
+
recommend using `backend`, as that's available beyond just `narwhals.stable.v1`.
|
| 1065 |
+
"""
|
| 1066 |
+
backend = cast("IntoBackend[Backend]", backend)
|
| 1067 |
+
return _stableify(nw_f.scan_parquet(source, backend=backend, **kwargs))
|
| 1068 |
+
|
| 1069 |
+
|
| 1070 |
+
__all__ = [
|
| 1071 |
+
"Array",
|
| 1072 |
+
"Binary",
|
| 1073 |
+
"Boolean",
|
| 1074 |
+
"Categorical",
|
| 1075 |
+
"DataFrame",
|
| 1076 |
+
"Date",
|
| 1077 |
+
"Datetime",
|
| 1078 |
+
"Decimal",
|
| 1079 |
+
"Duration",
|
| 1080 |
+
"Enum",
|
| 1081 |
+
"Expr",
|
| 1082 |
+
"Field",
|
| 1083 |
+
"Float32",
|
| 1084 |
+
"Float64",
|
| 1085 |
+
"Implementation",
|
| 1086 |
+
"Int8",
|
| 1087 |
+
"Int16",
|
| 1088 |
+
"Int32",
|
| 1089 |
+
"Int64",
|
| 1090 |
+
"Int128",
|
| 1091 |
+
"InvalidIntoExprError",
|
| 1092 |
+
"LazyFrame",
|
| 1093 |
+
"List",
|
| 1094 |
+
"Object",
|
| 1095 |
+
"Schema",
|
| 1096 |
+
"Series",
|
| 1097 |
+
"String",
|
| 1098 |
+
"Struct",
|
| 1099 |
+
"Time",
|
| 1100 |
+
"UInt8",
|
| 1101 |
+
"UInt16",
|
| 1102 |
+
"UInt32",
|
| 1103 |
+
"UInt64",
|
| 1104 |
+
"UInt128",
|
| 1105 |
+
"Unknown",
|
| 1106 |
+
"all",
|
| 1107 |
+
"all_horizontal",
|
| 1108 |
+
"any_horizontal",
|
| 1109 |
+
"coalesce",
|
| 1110 |
+
"col",
|
| 1111 |
+
"concat",
|
| 1112 |
+
"concat_str",
|
| 1113 |
+
"dependencies",
|
| 1114 |
+
"dtypes",
|
| 1115 |
+
"exceptions",
|
| 1116 |
+
"exclude",
|
| 1117 |
+
"format",
|
| 1118 |
+
"from_arrow",
|
| 1119 |
+
"from_dict",
|
| 1120 |
+
"from_dicts",
|
| 1121 |
+
"from_native",
|
| 1122 |
+
"from_numpy",
|
| 1123 |
+
"generate_temporary_column_name",
|
| 1124 |
+
"get_level",
|
| 1125 |
+
"get_native_namespace",
|
| 1126 |
+
"is_expr",
|
| 1127 |
+
"is_ordered_categorical",
|
| 1128 |
+
"len",
|
| 1129 |
+
"lit",
|
| 1130 |
+
"max",
|
| 1131 |
+
"max_horizontal",
|
| 1132 |
+
"maybe_align_index",
|
| 1133 |
+
"maybe_convert_dtypes",
|
| 1134 |
+
"maybe_get_index",
|
| 1135 |
+
"maybe_reset_index",
|
| 1136 |
+
"maybe_set_index",
|
| 1137 |
+
"mean",
|
| 1138 |
+
"mean_horizontal",
|
| 1139 |
+
"median",
|
| 1140 |
+
"min",
|
| 1141 |
+
"min_horizontal",
|
| 1142 |
+
"narwhalify",
|
| 1143 |
+
"new_series",
|
| 1144 |
+
"nth",
|
| 1145 |
+
"read_csv",
|
| 1146 |
+
"read_parquet",
|
| 1147 |
+
"scan_csv",
|
| 1148 |
+
"scan_parquet",
|
| 1149 |
+
"selectors",
|
| 1150 |
+
"show_versions",
|
| 1151 |
+
"sum",
|
| 1152 |
+
"sum_horizontal",
|
| 1153 |
+
"to_native",
|
| 1154 |
+
"to_py_scalar",
|
| 1155 |
+
"when",
|
| 1156 |
+
]
|