Skip to content
Open
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
22 changes: 22 additions & 0 deletions libpysal/weights/tests/test_adjlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,25 @@ def test_lat2w(self):
manual_neighbors = w.to_adjlist().groupby("focal").neighbor.agg(list).to_dict()
for focal, neighbors in w.neighbors.items():
assert set(manual_neighbors[focal]) == set(neighbors)

def test_from_adjlist_missing_weight_column(self):
"""Test that from_adjlist handles missing weight column correctly."""
import pandas as pd

adjlist = pd.DataFrame({"focal": [0, 0, 1, 1, 2], "neighbor": [1, 2, 0, 2, 0]})
# Should not raise AttributeError
w = weights.W.from_adjlist(adjlist)
assert w.weights[0] == [1, 1]
assert w.weights[1] == [1, 1]
assert w.weights[2] == [1]

def test_from_adjlist_custom_weight_column_missing(self):
"""Test that from_adjlist handles missing custom weight column."""
import pandas as pd

# Create adjlist without custom weight column
adjlist = pd.DataFrame({"focal": [0, 1], "neighbor": [1, 0]})
# Should not raise AttributeError when weight_col is specified but missing
w = weights.W.from_adjlist(adjlist, weight_col="custom_weight")
assert w.weights[0] == [1]
assert w.weights[1] == [1]
4 changes: 2 additions & 2 deletions libpysal/weights/weights.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,10 +368,10 @@ def from_adjlist(
"""
if weight_col is None:
weight_col = "weight"
try_weightcol = getattr(adjlist, weight_col)
if try_weightcol is None:
if weight_col not in adjlist.columns:
adjlist = adjlist.copy(deep=True)
adjlist["weight"] = 1
weight_col = "weight"
grouper = adjlist.groupby(focal_col)
neighbors = {}
weights = {}
Expand Down