Skip to content

Commit 5b1986d

Browse files
committed
Allow assignment of repeated values with equal index rhv
1 parent 6717fac commit 5b1986d

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/nested_pandas/nestedframe/core.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,12 @@ def __setitem__(self, key, value):
195195
if len(components) != 2:
196196
raise ValueError(f"Only one level of nesting is supported; given {key}")
197197
nested, field = components
198-
new_nested_series = self[nested].nest.with_flat_field(field, value)
198+
# Support a special case of embedding a base column into a nested column, with values being
199+
# repeated in each nested list-array.
200+
if isinstance(value, pd.Series) and self.index.equals(value.index):
201+
new_nested_series = self[nested].nest.with_filled_field(field, value)
202+
else:
203+
new_nested_series = self[nested].nest.with_flat_field(field, value)
199204
return super().__setitem__(nested, new_nested_series)
200205

201206
# Adding a new nested structure from a column

tests/nested_pandas/nestedframe/test_nestedframe.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def test_get_nested_column():
160160

161161

162162
def test_set_or_replace_nested_col():
163-
"""Test that __setitem__ can set or replace a column in a existing nested structure"""
163+
"""Test that __setitem__ can set or replace a column in an existing nested structure"""
164164

165165
base = NestedFrame(data={"a": [1, 2, 3], "b": [2, 4, 6]}, index=[0, 1, 2])
166166
c = [0, 2, 4, 1, 4, 3, 1, 4, 1]
@@ -188,6 +188,17 @@ def test_set_or_replace_nested_col():
188188
assert "e" in base.nested.nest.fields
189189
assert np.array_equal(base["nested.d"].values.to_numpy() * 2, base["nested.e"].values.to_numpy())
190190

191+
# test assignment a new column with list-repeated values
192+
base["nested.a"] = base["a"]
193+
194+
assert "a" in base.nested.nest.fields
195+
assert np.array_equal(np.unique(base["a"].to_numpy()), np.unique(base["nested.a"].to_numpy()))
196+
197+
# rest replacement with a list-repeated column
198+
base["nested.c"] = base["a"] + base["b"] - 99
199+
200+
assert np.array_equal(base["a"] + base["b"] - 99, np.unique(base["nested.c"].to_numpy()))
201+
191202

192203
def test_set_new_nested_col():
193204
"""Test that __setitem__ can create a new nested structure"""

0 commit comments

Comments
 (0)