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

sdks/python: enable named aggregation to deferred DataFrame groupby #33672

Conversation

mohamedawnallah
Copy link
Contributor

@mohamedawnallah mohamedawnallah commented Jan 20, 2025

Description

In this commit, we enable named aggregation to deferred DataFrame groupby.

Fixes #27278

Current Behavior

Before After
before after

Verifying Named Aggregation in Beam DataFrame GroupBy

import pandas as pd
import apache_beam as beam
from apache_beam.dataframe import convert

employee_data = {
    'Department': ['HR', 'HR', 'Engineering', 'Engineering', 'Sales', 'Sales'],
    'Salary': [50000, 55000, 70000, 75000, 60000, 65000],
    'Performance_Score': [8, 9, 7, 6, 8, 8],
    'Years_of_Experience': [2, 5, 8, 10, 3, 4]
}

employee_df = pd.DataFrame(employee_data)

CSV_HEADER = "Department,Mean_Salary,Median_Performance_Score,Total_Years_of_Experience"

def process_aggregated_data(row):
    """Convert aggregated data into a format suitable for CSV output."""
    department = row.Department
    salary = row.Mean_Salary
    performance_score = row.Median_Performance_Score
    experience = row.Total_Years_of_Experience
    return f"{department},{salary},{performance_score},{experience}"

with beam.Pipeline() as pipeline:
    # Convert pandas DataFrame to PCollection.
    employee_pcollection = convert.to_pcollection(employee_df, pipeline=pipeline)
    employee_beam_df = convert.to_dataframe(employee_pcollection)

    # Group by Department and aggregate functions:
    # mean salary, median performance score, and sum of years of experience
    with beam.dataframe.allow_non_parallel_operations():
        employee_aggregated_df = employee_beam_df.groupby('Department').agg(
            Mean_Salary=('Salary', 'mean'),
            Median_Performance_Score=('Performance_Score', 'median'),
            Total_Years_of_Experience=('Years_of_Experience', 'sum')
        ).reset_index()

    # Write the CSV, including header and data.
    csv_pcollection = (
        convert.to_pcollection(employee_aggregated_df)
        | beam.Map(lambda row: process_aggregated_data(row))
        | beam.io.WriteToText(
            "employee_data_grouped_by_department",
            file_name_suffix=".csv",
            header=CSV_HEADER
        )
    )

Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@mohamedawnallah mohamedawnallah force-pushed the enableNamedAggregationOnDeferredDataFrameGroupBy branch from 6e1a075 to eaede37 Compare January 20, 2025 01:45
Copy link
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

@mohamedawnallah mohamedawnallah force-pushed the enableNamedAggregationOnDeferredDataFrameGroupBy branch from eaede37 to b4b17f7 Compare January 20, 2025 02:57
@mohamedawnallah
Copy link
Contributor Author

Run Prism_Python PreCommit 3.9

Copy link
Contributor

Assigning reviewers. If you would like to opt out of this review, comment assign to next reviewer:

R: @tvalentyn for label python.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

Copy link
Contributor

@liferoad liferoad left a comment

Choose a reason for hiding this comment

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

Thanks!

Copy link
Contributor

Reminder, please take a look at this pr: @tvalentyn

@mohamedawnallah mohamedawnallah force-pushed the enableNamedAggregationOnDeferredDataFrameGroupBy branch from b4b17f7 to 7fde445 Compare February 2, 2025 12:05
In this commit, we enable named aggregated to
deferred DataFrame groupby operation.
In this commit, we test named aggregation to deferred
DataFrame groupby operation by passing None as function
and passing multiple kwargs aggregation functions on testing
columns.
@mohamedawnallah mohamedawnallah force-pushed the enableNamedAggregationOnDeferredDataFrameGroupBy branch from 7fde445 to 721f18e Compare February 2, 2025 12:21
@tvalentyn
Copy link
Contributor

tvalentyn commented Feb 3, 2025

Thanks for the change and follow-up, @mohamedawnallah . For future changes, please don't squash reviewed and unreviewed commits before the review process has concluded; instead, add follow-up commits on the branch, leaving prior commits as is.

Otherwise, reviewing is significantly harder.

@mohamedawnallah
Copy link
Contributor Author

For future changes, please don't squash reviewed and unreviewed commits before the review process has concluded; instead, add follow-up commits on the branch, leaving prior commits as is.

I will keep this in mind next time, Thanks 🙏

Otherwise, reviewing is significantly harder.

Thanks for your patience @tvalentyn 🙏

@liferoad liferoad merged commit df13ffe into apache:master Feb 3, 2025
91 checks passed
tomstepp pushed a commit to tomstepp/apache-beam that referenced this pull request Feb 3, 2025
…pache#33672)

* sdks/python: enable named aggregation

In this commit, we enable named aggregated to
deferred DataFrame groupby operation.

* sdks/python: test named aggregation

In this commit, we test named aggregation to deferred
DataFrame groupby operation by passing None as function
and passing multiple kwargs aggregation functions on testing
columns.
@mohamedawnallah mohamedawnallah deleted the enableNamedAggregationOnDeferredDataFrameGroupBy branch February 11, 2025 15:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: DataFramegroupby does not support named aggregation
3 participants