-
Notifications
You must be signed in to change notification settings - Fork 16
Adding DataFrameMixin for improved reusability/encapsulation #27
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
9c2b281
change from types to types_ to avoid import issues
adamamer20 9546b10
creation of DataFrameMixin
adamamer20 a716118
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] a9c9925
removing space types (has it's own PR)
adamamer20 cecf5af
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 4722edb
update types with types_
adamamer20 21c5ef8
Moved agentset to library folder
adamamer20 831324a
update __init__
adamamer20 853a19e
remove geopandas
adamamer20 7d128a8
removed gpd
adamamer20 783a717
Merge branch 'main' into dataframe-mixin
adamamer20 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
import pandas as pd | ||
from typing_extensions import Any | ||
from typing import Literal | ||
from collections.abc import Collection, Iterator, Sequence | ||
|
||
from mesa_frames.abstract.mixin import DataFrameMixin | ||
from mesa_frames.types_ import PandasMaskLike | ||
|
||
|
||
class PandasMixin(DataFrameMixin): | ||
def _df_add_columns( | ||
self, original_df: pd.DataFrame, new_columns: list[str], data: Any | ||
) -> pd.DataFrame: | ||
original_df[new_columns] = data | ||
return original_df | ||
|
||
def _df_combine_first( | ||
self, original_df: pd.DataFrame, new_df: pd.DataFrame, index_cols: list[str] | ||
) -> pd.DataFrame: | ||
return original_df.combine_first(new_df) | ||
|
||
def _df_concat( | ||
self, | ||
dfs: Collection[pd.DataFrame], | ||
how: Literal["horizontal"] | Literal["vertical"] = "vertical", | ||
ignore_index: bool = False, | ||
) -> pd.DataFrame: | ||
return pd.concat( | ||
dfs, axis=0 if how == "vertical" else 1, ignore_index=ignore_index | ||
) | ||
|
||
def _df_constructor( | ||
self, | ||
data: Sequence[Sequence] | dict[str | Any] | None = None, | ||
columns: list[str] | None = None, | ||
index_col: str | list[str] | None = None, | ||
dtypes: dict[str, Any] | None = None, | ||
) -> pd.DataFrame: | ||
df = pd.DataFrame(data=data, columns=columns).astype(dtypes) | ||
if index_col: | ||
df.set_index(index_col) | ||
return df | ||
|
||
def _df_get_bool_mask( | ||
self, | ||
df: pd.DataFrame, | ||
index_col: str, | ||
mask: PandasMaskLike = None, | ||
negate: bool = False, | ||
) -> pd.Series: | ||
if isinstance(mask, pd.Series) and mask.dtype == bool and len(mask) == len(df): | ||
result = mask | ||
elif isinstance(mask, pd.DataFrame): | ||
if mask.index.name == index_col: | ||
result = pd.Series(df.index.isin(mask.index), index=df.index) | ||
elif index_col in mask.columns: | ||
result = pd.Series(df.index.isin(mask[index_col]), index=df.index) | ||
else: | ||
raise ValueError( | ||
f"A DataFrame mask must have a column/index with name {index_col}" | ||
) | ||
elif mask is None or mask == "all": | ||
result = pd.Series(True, index=df.index) | ||
elif isinstance(mask, Sequence): | ||
result = pd.Series(df.index.isin(mask), index=df.index) | ||
else: | ||
result = pd.Series(df.index.isin([mask]), index=df.index) | ||
|
||
if negate: | ||
result = ~result | ||
|
||
return result | ||
|
||
def _df_get_masked_df( | ||
self, | ||
df: pd.DataFrame, | ||
index_col: str, | ||
mask: PandasMaskLike | None = None, | ||
columns: list[str] | None = None, | ||
negate: bool = False, | ||
) -> pd.DataFrame: | ||
b_mask = self._df_get_bool_mask(df, index_col, mask, negate) | ||
if columns: | ||
return df.loc[b_mask, columns] | ||
return df.loc[b_mask] | ||
|
||
def _df_iterator(self, df: pd.DataFrame) -> Iterator[dict[str, Any]]: | ||
for index, row in df.iterrows(): | ||
row_dict = row.to_dict() | ||
row_dict["unique_id"] = index | ||
yield row_dict | ||
|
||
def _df_remove( | ||
self, | ||
df: pd.DataFrame, | ||
ids: Sequence[Any], | ||
index_col: str | None = None, | ||
) -> pd.DataFrame: | ||
return df[~df.index.isin(ids)] | ||
|
||
def _df_sample( | ||
self, | ||
df: pd.DataFrame, | ||
n: int | None = None, | ||
frac: float | None = None, | ||
with_replacement: bool = False, | ||
shuffle: bool = False, | ||
seed: int | None = None, | ||
) -> pd.DataFrame: | ||
return df.sample( | ||
n=n, frac=frac, replace=with_replacement, shuffle=shuffle, random_state=seed | ||
) | ||
|
||
def _srs_constructor( | ||
self, | ||
data: Sequence[Sequence] | None = None, | ||
name: str | None = None, | ||
dtype: Any | None = None, | ||
index: Sequence[Any] | None = None, | ||
) -> pd.Series: | ||
return pd.Series(data, name=name, dtype=dtype, index=index) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.