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 value_counts for Pandas 2 #28500

Merged
merged 1 commit into from
Sep 19, 2023
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
17 changes: 14 additions & 3 deletions sdks/python/apache_beam/dataframe/frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -2341,8 +2341,13 @@ def value_counts(

result = column.groupby(column, dropna=dropna).size()

# groupby.size() names the index, which we don't need
result.index.name = None
# Pandas 2 introduces new naming for the results.
if PD_VERSION >= (2, 0):
result.index.name = getattr(self, "name", None)
result.name = "proportion" if normalize else "count"
caneff marked this conversation as resolved.
Show resolved Hide resolved
else:
# groupby.size() names the index, which we don't need
result.index.name = None

if normalize:
return result / column.length()
Expand Down Expand Up @@ -3994,12 +3999,18 @@ def value_counts(self, subset=None, sort=False, normalize=False,
columns = subset or list(self.columns)

if dropna:
dropped = self.dropna()
# Must include subset here because otherwise we spuriously drop NAs due
# to columns outside our subset.
dropped = self.dropna(subset=subset)
caneff marked this conversation as resolved.
Show resolved Hide resolved
else:
dropped = self

result = dropped.groupby(columns, dropna=dropna).size()

# Pandas 2 introduces new naming for the results.
if PD_VERSION >= (2,0):
result.name = "proportion" if normalize else "count"

if normalize:
return result/dropped.length()
else:
Expand Down
2 changes: 2 additions & 0 deletions sdks/python/apache_beam/dataframe/frames_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,8 @@ def test_value_counts_with_nans(self):

self._run_test(lambda df: df.value_counts(), df)
self._run_test(lambda df: df.value_counts(normalize=True), df)
# Ensure we don't drop rows due to nan values in unused columns.
self._run_test(lambda df: df.value_counts('num_wings'), df)

if PD_VERSION >= (1, 3):
# dropna=False is new in pandas 1.3
Expand Down
Loading