You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Pandas DataFrame中实现单元格/列聚合的方法问询

Aggregating DataFrame Cell Values into Single Cells (Multi-Word Column Names)

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 CategoryNut ButterSnack BarGranola Bar
BreakfastPeanut, AlmondOat Crunch, Chocolate ChipHoney Oat, Cinnamon Spice
On-the-Go SnackCashewFruit FusionVanilla 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:53:13