Skip to content

✨ add pandas.Series #68

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 34 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
89a2c38
Add support and test for pd.Series
EkberHasanov Jun 25, 2023
b726b19
Adding docs for basic usage
EkberHasanov Jun 25, 2023
24bf87a
Fix documentation
EkberHasanov Jun 25, 2023
1bb8a71
Add pandas to optional dependencies
EkberHasanov Jun 25, 2023
bc37f7f
fix python3.8 issues
EkberHasanov Jun 26, 2023
43be7f6
fix py3.7 issues
EkberHasanov Jun 26, 2023
50b0547
fix macos error
EkberHasanov Jun 27, 2023
16aa656
fix indentation error in ci.yml
EkberHasanov Jun 27, 2023
0d899c9
ci: fix dependency issue in macos
EkberHasanov Jun 30, 2023
33f45f2
improve test coverage to 100%
EkberHasanov Jun 30, 2023
98e58d6
🔧 update code
yezz123 Jun 30, 2023
b4a35ac
🍱 update requirements
yezz123 Jun 30, 2023
1660ca7
Merge branch 'main' into type/pandas
yezz123 Jun 30, 2023
b1e04f0
🍱 Fix Requirements
yezz123 Jun 30, 2023
2ac57cd
🍱 Fix Requirements
yezz123 Jun 30, 2023
339c71b
.
yezz123 Jun 30, 2023
7129b91
fix
yezz123 Jun 30, 2023
c9c4f12
Update pydantic_extra_types/pandas_types.py
yezz123 Jul 1, 2023
cc9dac0
Inheriting directly from pd.Series
EkberHasanov Jul 6, 2023
501c173
Merge branch 'main' into type/pandas
EkberHasanov Jul 6, 2023
09e073d
delete extra files
EkberHasanov Jul 12, 2023
b15b3d0
upgrading version of pandas
EkberHasanov Feb 25, 2024
2718471
Merge branch 'main' into type/pandas
EkberHasanov Feb 25, 2024
8e408bc
Update pyproject.txt
EkberHasanov Feb 25, 2024
7b4433f
Update test_json_schema.py
EkberHasanov Feb 25, 2024
6cff2d7
Update linting.in
EkberHasanov Feb 25, 2024
3d7b805
adding pandas-stubs
EkberHasanov Feb 25, 2024
b751633
fix versions
EkberHasanov Feb 25, 2024
d78fc5a
resolve version issue
EkberHasanov Feb 25, 2024
6a55cd2
upgrading version of numpy
EkberHasanov Feb 25, 2024
ba7a941
fixing some issues
EkberHasanov Feb 25, 2024
933540a
change core_schema func
EkberHasanov Feb 29, 2024
25da211
Merge branch 'main' into type/pandas
EkberHasanov Feb 29, 2024
811d664
Update test_json_schema.py
EkberHasanov Feb 29, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,21 @@ jobs:
with:
python-version: ${{ matrix.python-version }}

- name: Install bzip2 on macOS
if: matrix.os == 'macos'
run: brew install bzip2


- name: Set environment variables
if: matrix.os == 'macos'
run: |
export LDFLAGS="-L/usr/local/opt/bzip2/lib"
export CPPFLAGS="-I/usr/local/opt/bzip2/include"

- run: |
pip install -r requirements/pyproject.txt && pip install -r requirements/testing.txt


- run: pip freeze

- run: make test
Expand Down
25 changes: 25 additions & 0 deletions docs/pandas_types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

The `Series` class provides support for working with pandas Series objects.

```py
import pandas as pd
from pydantic import BaseModel

from pydantic_extra_types.pandas_types import Series


class MyData(BaseModel):
numbers: Series


data = {"numbers": pd.Series([1, 2, 3, 4, 5])}
my_data = MyData(**data)

print(my_data.numbers)
# > 0 1
# > 1 2
# > 2 3
# > 3 4
# > 4 5
# > dtype: int64
```
3 changes: 2 additions & 1 deletion pydantic_extra_types/isbn.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""
The `pydantic_extra_types.isbn` module provides functionality to recieve and validate ISBN.

ISBN (International Standard Book Number) is a numeric commercial book identifier which is intended to be unique. This module provides a ISBN type for Pydantic models.
ISBN (International Standard Book Number) is a numeric commercial book identifier which is intended to be unique.
This module provides a ISBN type for Pydantic models.
"""

from __future__ import annotations
Expand Down
22 changes: 22 additions & 0 deletions pydantic_extra_types/pandas_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from __future__ import annotations

from typing import Any

import pandas as pd
from pydantic import GetCoreSchemaHandler
from pydantic_core import core_schema


class Series(pd.Series): # type: ignore
@classmethod
def __get_pydantic_core_schema__(
cls, source: type[Any], handler: GetCoreSchemaHandler
) -> core_schema.BeforeValidatorFunctionSchema:
return core_schema.general_before_validator_function(
cls._validate,
core_schema.any_schema(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is the best we can do. Is it? A series should be an array of some type, and I guess we are able to get this type as well.

)

@classmethod
def _validate(cls, __input_value: Any, _: core_schema.ValidationInfo) -> Series:
return cls(__input_value)
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ dynamic = ['version']
[project.optional-dependencies]
all = [
'phonenumbers>=8,<9',
'pycountry>=22,<23',
'pandas==2.2.1',
'pycountry>=23',
'python-ulid>=1,<2; python_version<"3.9"',
'python-ulid>=1,<3; python_version>="3.9"',
Expand Down
1 change: 1 addition & 0 deletions requirements/linting.in
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pre-commit
mypy
annotated-types
ruff
pandas-stubs
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Likely not needed on pandas >= 2.

12 changes: 11 additions & 1 deletion requirements/linting.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#
# This file is autogenerated by pip-compile with Python 3.11
# This file is autogenerated by pip-compile with Python 3.10
# by the following command:
#
# pip-compile --no-emit-index-url --output-file=requirements/linting.txt requirements/linting.in
Expand All @@ -20,6 +20,16 @@ mypy-extensions==1.0.0
# via mypy
nodeenv==1.8.0
# via pre-commit
numpy==1.26.4
# via pandas-stubs
pandas-stubs==2.2.0.240218
# via -r requirements/linting.in
packaging==23.2
# via black
pathspec==0.12.1
# via -r requirements/linting.in
pyupgrade==3.15.0

platformdirs==4.2.0
# via virtualenv
pre-commit==3.6.2
Expand Down
4 changes: 3 additions & 1 deletion requirements/pyproject.txt
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#
# This file is autogenerated by pip-compile with Python 3.11
# This file is autogenerated by pip-compile with Python 3.10
# by the following command:
#
# pip-compile --extra=all --no-emit-index-url --output-file=requirements/pyproject.txt pyproject.toml
#
annotated-types==0.6.0
# via pydantic
pandas==2.0.3
# via pydantic-extra-types (pyproject.toml)
pendulum==3.0.0
# via pydantic-extra-types (pyproject.toml)
phonenumbers==8.13.31
Expand Down
7 changes: 1 addition & 6 deletions tests/test_json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,7 @@
(
ISBN,
{
'properties': {
'x': {
'title': 'X',
'type': 'string',
}
},
'properties': {'x': {'title': 'X'}},
'required': ['x'],
'title': 'Model',
'type': 'object',
Expand Down
115 changes: 115 additions & 0 deletions tests/test_pandas_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import pandas as pd
import pytest
from pydantic import BaseModel

from pydantic_extra_types.pandas_types import Series


@pytest.fixture(scope='session', name='SeriesModel')
def series_model_fixture():
class SeriesModel(BaseModel):
data: Series

return SeriesModel


@pytest.mark.parametrize(
'data, expected',
[
([1, 2, 3], [1, 2, 3]),
([], []),
([10, 20, 30, 40], [10, 20, 30, 40]),
],
)
def test_series_creation(data, expected):
if pd.__version__ <= '1.5.3' and data == []:
s = Series([1])
expected = [1]
else:
s = Series(data)
assert isinstance(s, Series)
assert isinstance(s, pd.Series)
assert s.tolist() == expected


def test_series_repr():
data = [1, 2, 3]
s = Series(data)
assert repr(s) == repr(pd.Series(data))


def test_series_attribute_access():
data = [1, 2, 3]
s = Series(data)
assert s.sum() == pd.Series(data).sum()


def test_series_equality():
data = [1, 2, 3]
s1 = Series(data)
s2 = Series(data)
assert s1.equals(other=s2)
assert s2.equals(pd.Series(data))


def test_series_addition():
data1 = [1, 2, 3]
data2 = [4, 5, 6]
s1 = Series(data1)
s2 = Series(data2)
s3 = s1 + s2
assert isinstance(s3, pd.Series)
assert s3.tolist() == [5, 7, 9]


@pytest.mark.parametrize(
'data, other, expected',
[
([1, 2, 3], [4, 5, 6], [5, 7, 9]),
([10, 20, 30], (1, 2, 3), [11, 22, 33]),
([5, 10, 15], pd.Series([1, 2, 3]), [6, 12, 18]),
],
)
def test_series_addition_with_types(data, other, expected):
s = Series(data)
result = s + other
assert isinstance(result, pd.Series)
assert result.tolist() == expected


@pytest.mark.parametrize(
'data, other',
[
([1, 2, 3], 'invalid'), # Invalid type for addition
([1, 2, 3], {'a': 1, 'b': 2}), # Invalid type for addition
],
)
def test_series_addition_invalid_type_error(data, other) -> None:
s = Series(data)
with pytest.raises(TypeError):
s + other


@pytest.mark.parametrize(
'data, other',
[
([1, 2, 3], []),
],
)
def test_series_addition_invalid_value_error(data, other) -> None:
s = Series(data)
with pytest.raises(ValueError):
s + other


def test_valid_series_model(SeriesModel) -> None:
model = SeriesModel(data=[1, 2, 4])
assert isinstance(model.data, pd.Series)
assert model.data.equals(pd.Series([1, 2, 4]))


def test_valid_series_model_with_pd_series(SeriesModel) -> None:
s = pd.Series([1, 2, 4])
model = SeriesModel(data=s)
assert isinstance(model.data, pd.Series)
assert model.data.equals(s)