Skip to content
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
4 changes: 4 additions & 0 deletions changelog_entry.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
- bump: patch
changes:
fixed:
- Allowed a MicroDataFrame to handle an empty index subset
4 changes: 2 additions & 2 deletions docs/gini.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"# Create sample data\n",
"x = [10, 20, 30, 40, 100]\n",
"w = [1, 2, 3, 4, 5]\n",
"df = pd.DataFrame({'x': x, 'w': w})"
"df = pd.DataFrame({\"x\": x, \"w\": w})"
]
},
{
Expand Down Expand Up @@ -80,7 +80,7 @@
"outputs": [],
"source": [
"# Create a MicroDataFrame\n",
"mdf_df = mdf.MicroDataFrame(df, weights='w')\n",
"mdf_df = mdf.MicroDataFrame(df, weights=\"w\")\n",
"\n",
"# Access column as MicroSeries and calculate gini\n",
"print(f\"Gini from MicroDataFrame column: {mdf_df.x.gini():.4f}\")"
Expand Down
12 changes: 7 additions & 5 deletions microdf/microdataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,15 @@ def set_weight_col(
def __getitem__(
self, key: Union[str, List]
) -> Union[pd.Series, pd.DataFrame]:
# Let pandas handle the initial slicing
result = super().__getitem__(key)

# If the result is a DataFrame, re-synchronize the weights
if isinstance(result, pd.DataFrame):
try:
weights = self.weights[key]
except Exception:
weights = self.weights
return MicroDataFrame(result, weights=weights)
new_weights = self.weights.reindex(result.index)
return MicroDataFrame(result, weights=new_weights)

# Otherwise, the result is a Series or a scalar, so just return it
return result

def catch_series_relapse(self) -> None:
Expand Down
9 changes: 9 additions & 0 deletions microdf/tests/test_microseries_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ def test_df_init() -> None:
assert df.a.mean() == np.average(arr, weights=w)


def test_handles_empty_index() -> None:
arr = np.array([0, 1, 1])
w = np.array([3, 0, 9])
df = mdf.MicroDataFrame({"a": arr}, weights=w)

empty_index = pd.Index([])
df[empty_index] # Implicit assert; checking for ValueError


def test_series_getitem() -> None:
arr = np.array([0, 1, 1])
w = np.array([3, 0, 9])
Expand Down