Skip to content

Commit

Permalink
Merge pull request #746 from martinfleis/categorical-lag-fix
Browse files Browse the repository at this point in the history
BUG: fix categorical lag for custom index
  • Loading branch information
sjsrey authored Jul 11, 2024
2 parents f806487 + 77f38e1 commit 3ef7b63
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
7 changes: 5 additions & 2 deletions libpysal/graph/_spatial_lag.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,12 @@ def _lag_spatial(graph, y, categorical=False, ties="raise"):
):
categorical = True
if categorical:
if isinstance(y, np.ndarray):
y = pd.Series(y, index=graph.unique_ids)

df = pd.DataFrame(data=graph.adjacency)
df["neighbor_label"] = y[graph.adjacency.index.get_level_values(1)]
df["own_label"] = y[graph.adjacency.index.get_level_values(0)]
df["neighbor_label"] = y.loc[graph.adjacency.index.get_level_values(1)].values
df["own_label"] = y.loc[graph.adjacency.index.get_level_values(0)].values
df["neighbor_idx"] = df.index.get_level_values(1)
df["focal_idx"] = df.index.get_level_values(0)
gb = df.groupby(["focal", "neighbor_label"]).count().groupby(level="focal")
Expand Down
6 changes: 6 additions & 0 deletions libpysal/graph/tests/test_spatial_lag.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,9 @@ def test_ties_raise(self):
with pytest.raises(ValueError, match="There are 2 ties that must be broken"):
self.yc[3] = "a" # create ties
_lag_spatial(self.gc, self.yc, categorical=True)

def test_categorical_custom_index(self):
expected = np.array(["bar", "foo", "bar", "foo"])
np.testing.assert_array_equal(
expected, self.g.lag(["foo", "bar", "foo", "foo"])
)

0 comments on commit 3ef7b63

Please sign in to comment.