Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix PandasBlocks implementation for missmatching categories #81

Merged
merged 2 commits into from
Jul 15, 2024
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
13 changes: 12 additions & 1 deletion partd/pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,17 @@ def join(dfs):
if not dfs:
return pd.DataFrame()
else:
return pd.concat(dfs)
result = pd.concat(dfs)
dtypes = {
col: "category"
for col in result.columns
if (
isinstance(dfs[0][col].dtype, pd.CategoricalDtype)
and not isinstance(result[col].dtype, pd.CategoricalDtype)
)
}
if dtypes:
result = result.astype(dtypes)
return result

PandasBlocks = partial(Encode, serialize, deserialize, join)
14 changes: 14 additions & 0 deletions partd/tests/test_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,17 @@ def test_index_non_numeric_extension_types(dtype):
df.index = df.index.astype(dtype)
df2 = deserialize(serialize(df))
tm.assert_frame_equal(df, df2)


def test_categorical_concat():
pytest.importorskip("pandas", minversion="2")

df1 = pd.DataFrame({"a": ["x", "y"]}, dtype="category")
df2 = pd.DataFrame({"a": ["y", "z"]}, dtype="category")

with PandasBlocks() as p:
p.append({'x': df1})
p.append({'x': df2})

result = p.get(["x"])
pd.testing.assert_frame_equal(result[0], pd.concat([df1, df2]).astype("category"))
Loading