如何编写函数实现两列匹配后提取对应分组最小数值?
Solution for Grouped Minimum Value Assignment
Absolutely! This is a common tabular data manipulation task, and it’s easy to implement using Python’s pandas library—perfect for handling this kind of grouped aggregation and value propagation.
Here’s a complete, reusable function that does exactly what you need:
import pandas as pd def add_group_min_column(df, group_cols, value_col, new_col_name): """ Adds a column with the minimum value of a specified column for each group. Args: df (pd.DataFrame): Input DataFrame containing your data. group_cols (list): List of column names to group by (e.g., ['Col1', 'Col2']). value_col (str): Name of the column to compute the minimum from. new_col_name (str): Name for the new column with the group minimum. Returns: pd.DataFrame: Original DataFrame with the new column added. """ # Calculate the minimum value for each group and propagate it to all rows in the group group_mins = df.groupby(group_cols)[value_col].transform('min') # Attach the computed values as a new column df[new_col_name] = group_mins return df
How to use this function with your sample data:
First, let's set up your sample input data as a DataFrame:
# Sample input data data = { 'Col1': ['Fruit', 'Fruit', 'Fruit', 'Fruit', 'Fruit', 'Car', 'Car'], 'Col2': ['Pear', 'Pear', 'Pear', 'Kiwi', 'Kiwi', 'Honda', 'Honda'], 'NUMBER1': [2, 3, 4, 7, 9, 4, 5] } df = pd.DataFrame(data)
Then call the function with your specific parameters:
processed_df = add_group_min_column(df, ['Col1', 'Col2'], 'NUMBER1', 'COMPARED NUMBER')
Result:
Printing processed_df will give you exactly the output you requested:
Col1 Col2 NUMBER1 COMPARED NUMBER 0 Fruit Pear 2 2 1 Fruit Pear 3 2 2 Fruit Pear 4 2 3 Fruit Kiwi 7 7 4 Fruit Kiwi 9 7 5 Car Honda 4 4 6 Car Honda 5 4
Key details:
- The
transform('min')method is the core of this solution: it calculates the minimum value for each group, then broadcasts that value back to every row in the original group (instead of returning a condensed group-level result like a standardgroupby().min()would). - The function is flexible—you can reuse it with different grouping columns, value columns, or new column names without rewriting the core logic.
内容的提问来源于stack exchange,提问作者Hugo Pablo
相关产品推荐
相关产品推荐

