Skip to content

Update types for Series.unstack, DataFrame.stack, and DataFrame.unstack #1259

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

Merged
merged 3 commits into from
Jun 20, 2025

Conversation

stephenlrandall
Copy link
Contributor


def test_series_unstack() -> None:
df = pd.DataFrame([[1, 3, 5], [2, 4, 6]])
s = df.transpose().stack([*range(df.index.nlevels)])
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you do check(assert_type(s, pd.Series), pd.Series, np.int64) here? (I think that's the right type)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That fails with:

tests/test_series.py:3917: error: Expression is of type "DataFrame | Series[Any]", not "Series[Any]"  [assert-type]
Found 1 error in 1 file (checked 224 source files)

What I can do instead is:

def test_series_unstack() -> None:
    df = pd.DataFrame([[1, 3, 5], [2, 4, 6]])
    s = cast(pd.Series, df.transpose().stack([*range(df.index.nlevels)]))
    check(assert_type(s, pd.Series), pd.Series, np.int64)
    check(
        assert_type(
            s.unstack([*range(s.index.nlevels // 2)]),
            pd.DataFrame,
        ),
        pd.DataFrame,
    )

where I explicitly cast the stacked object to a Series. Or would you rather have something else there?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replace s = cast(pd.Series, df.transpose().stack([*range(df.index.nlevels)])) with

s = df.transpose().stack([*range(df.index.nlevels)]))
check(assert_type(s, Union[pd.Series, pd.DataFrame), pd.Series)

This then says from a typing perspective, you could get the Union, but at runtime, you will get a Series

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense -- updated the test.

Copy link
Collaborator

@Dr-Irv Dr-Irv left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Dr-Irv Dr-Irv merged commit 1b1c127 into pandas-dev:main Jun 20, 2025
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Incorrect type for Series.unstack
2 participants