Skip to content

Commit aa34af1

Browse files
authored
Merge pull request #147 from lincc-frameworks/from_flat_df
fix from_flat for pd input
2 parents 6101d39 + cd7ca7e commit aa34af1

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/nested_pandas/nestedframe/core.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,10 @@ def from_flat(cls, df, base_columns, nested_columns=None, index=None, name="nest
210210
# drop duplicates on index
211211
out_df = df[base_columns][~df.index.duplicated(keep="first")]
212212

213+
# Convert df to NestedFrame if needed
214+
if not isinstance(out_df, NestedFrame):
215+
out_df = NestedFrame(out_df)
216+
213217
# add nested
214218
if nested_columns is None:
215219
nested_columns = [col for col in df.columns if col not in base_columns]

tests/nested_pandas/nestedframe/test_nestedframe.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -285,13 +285,21 @@ def test_add_nested_for_empty_df():
285285
assert_frame_equal(new_base.nested.nest.to_flat(), nested.astype(pd.ArrowDtype(pa.float64())))
286286

287287

288+
@pytest.mark.parametrize("pandas", [False, True])
288289
@pytest.mark.parametrize("index", [None, "a", "c"])
289-
def test_from_flat(index):
290+
def test_from_flat(index, pandas):
290291
"""Test the NestedFrame.from_flat functionality"""
291-
nf = NestedFrame(
292-
{"a": [1, 1, 1, 2, 2], "b": [2, 2, 2, 4, 4], "c": [1, 2, 3, 4, 5], "d": [2, 4, 6, 8, 10]},
293-
index=[0, 0, 0, 1, 1],
294-
)
292+
293+
if pandas:
294+
nf = pd.DataFrame(
295+
{"a": [1, 1, 1, 2, 2], "b": [2, 2, 2, 4, 4], "c": [1, 2, 3, 4, 5], "d": [2, 4, 6, 8, 10]},
296+
index=[0, 0, 0, 1, 1],
297+
)
298+
else:
299+
nf = NestedFrame(
300+
{"a": [1, 1, 1, 2, 2], "b": [2, 2, 2, 4, 4], "c": [1, 2, 3, 4, 5], "d": [2, 4, 6, 8, 10]},
301+
index=[0, 0, 0, 1, 1],
302+
)
295303

296304
out_nf = NestedFrame.from_flat(nf, base_columns=["a", "b"], index=index, name="new_nested")
297305

0 commit comments

Comments
 (0)