在Pandas DataFrame中实现单元格/列聚合的方法问询
Got it, let's break down how to solve this aggregation problem with pandas—since your column names are multi-word like Nut Butter instead of single letters, I'll use realistic, relatable examples to make this actionable.
Example Scenario
Let's say your input DataFrame looks like this (with multi-word column names as you described):
import pandas as pd # Sample input DataFrame df = pd.DataFrame({ 'Product Category': ['Breakfast', 'Breakfast', 'On-the-Go Snack'], 'Nut Butter': ['Peanut', 'Almond', 'Cashew'], 'Snack Bar': ['Oat Crunch', 'Chocolate Chip', 'Fruit Fusion'], 'Granola Bar': ['Honey Oat', 'Cinnamon Spice', 'Vanilla Almond'] })
Goal
You want to group rows by a key column (like Product Category) and aggregate all values from each multi-word column into a single comma-separated cell, resulting in:
| Product Category | Nut Butter | Snack Bar | Granola Bar |
|---|---|---|---|
| Breakfast | Peanut, Almond | Oat Crunch, Chocolate Chip | Honey Oat, Cinnamon Spice |
| On-the-Go Snack | Cashew | Fruit Fusion | Vanilla Almond |
Solution Code
Use groupby() combined with agg() to concatenate values into single cells. For string columns, a simple ', '.join works perfectly:
# Group by the key column and aggregate values into single cells aggregated_df = df.groupby('Product Category').agg(', '.join).reset_index() # View the result print(aggregated_df)
Handling Numeric Columns or Missing Values
If some columns contain numeric values, convert them to strings first before aggregating. You can also drop missing values to keep your clean:
# Convert numeric columns to strings and aggregate, skipping NaNs aggregated_df = df.groupby('Product Category').agg( lambda x: ', '.join(map(str, x.dropna())) ).reset_index()
Alternative: Aggregate All Columns into One Single Column
If you want to combine values from all multi-word columns into a single new column (e.g., All Products), use apply() row-wise:
# Combine all product columns into one cell per row df['All Products'] = df[['Nut Butter', 'Snack Bar', 'Granola Bar']].apply( lambda row: ', '.join(row.dropna().astype(str)), axis=1 )
This approach is flexible, works seamlessly with multi-word column names, and adapts to most common aggregation needs you might have.
内容的提问来源于stack exchange,提问作者Rookie_123

