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

Preserve column names in empty Dataframe #61143

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

kpvenkat47
Copy link

Description

Updates pandas/core/frame.py to preserve column names in empty DataFrames when nrows == 0. Changed from return Cls() to return Cls(columns=columns).

Changes Made

  • Modified if nrows == 0 in core/frame.py.
  • Added test in tests/frame/test_constructors.py.

Testing

  • Added test case for empty DataFrame column retention.
  • Verified locally with pytest.

…if nrows == 0' to return Cls(columns=columns) in core/frame.py. - Added test to verify column preservation.
Copy link
Member

@rhshadrach rhshadrach left a comment

Choose a reason for hiding this comment

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

Thanks for the PR! When making a PR, follow these steps here:

https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#making-a-pull-request

namely step 4.

Comment on lines +2 to +6
def test_empty_df_preserve_col():
rows = []
df = pd.DataFrame.from_records(iter(rows), columns=['col_1', 'Col_2'], nrows=0)
assert list(df.columns)==['col_1', 'Col_2']
assert len(df) == 0
Copy link
Member

Choose a reason for hiding this comment

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

Can you follow the dev docs here: https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests

Namely, search the current tests for from_records and that should give a good indication of where to place this test.

@rhshadrach rhshadrach added IO Data IO issues that don't fit into a more specific label Bug labels Mar 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug IO Data IO issues that don't fit into a more specific label
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants