Skip to content
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

Convert NaN to None in TimeSeries Models #11

Merged
merged 2 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion openenergyid/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Open Energy ID Python SDK."""

__version__ = "0.1.14"
__version__ = "0.1.15"

from .enums import Granularity
from .models import TimeDataFrame, TimeSeries
Expand Down
24 changes: 18 additions & 6 deletions openenergyid/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from typing import Self

import pandas as pd
from pydantic import BaseModel
from pydantic import BaseModel, field_validator


class TimeSeriesBase(BaseModel):
Expand Down Expand Up @@ -47,7 +47,7 @@ def from_json(cls, string: str, **kwargs) -> Self:

@overload
@classmethod
def from_json(cls, path: str, **kwargs) -> Self:
def from_json(cls, *, path: str, **kwargs) -> Self:
"""Load from a JSON file."""

@classmethod
Expand All @@ -66,12 +66,18 @@ class TimeSeries(TimeSeriesBase):
"""Time series data with a single column."""

name: str | None = None
data: list[float]
data: list[float | None]

@field_validator("data")
@classmethod
def replace_nan_with_none(cls, data: list[float]) -> list[float | None]:
"""Replace NaN values with None."""
return [None if pd.isna(value) else value for value in data]

@classmethod
def from_pandas(cls, data: pd.Series) -> Self:
"""Create from a Pandas Series."""
return cls.model_construct(name=data.name, data=data.tolist(), index=data.index.tolist())
return cls(name=str(data.name), data=data.tolist(), index=data.index.tolist())

def to_pandas(self, timezone: str = "UTC") -> pd.Series:
"""Convert to a Pandas Series."""
Expand All @@ -84,12 +90,18 @@ class TimeDataFrame(TimeSeriesBase):
"""Time series data with multiple columns."""

columns: list[str]
data: list[list[float]]
data: list[list[float | None]]

@field_validator("data")
@classmethod
def replace_nan_with_none(cls, data: list[list[float]]) -> list[list[float | None]]:
"""Replace NaN values with None."""
return [[None if pd.isna(value) else value for value in row] for row in data]

@classmethod
def from_pandas(cls, data: pd.DataFrame) -> Self:
"""Create from a Pandas DataFrame."""
return cls.model_construct(
return cls(
columns=data.columns.tolist(), data=data.values.tolist(), index=data.index.tolist()
)

Expand Down
Loading