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

Pandas分组聚合后自定义列名格式(将item1_last转为last_item1)的更优实现方法咨询

How to Get Aggregated Columns in last_item1/count_item1 Format with Pandas Groupby

Absolutely, there are cleaner and more intuitive ways to achieve your desired column naming format. Let's break down two solid approaches:

1. Reverse the Column Name Mapping (Quick Fix for Your Existing Code)

Your current code joins the column levels in the order original_col_aggfunc—we just need to flip that order when mapping the columns:

import pandas as pd
import numpy as np

df = pd.DataFrame({"item":['a','a','a','b'],"item1":['b','d',np.nan,'c']})
df_grp = df.groupby("item").agg({'item1' : ['last','count']})
# Flip the order when joining column levels
df_grp.columns = df_grp.columns.map(lambda x: f"{x[1]}_{x[0]}")
result = df_grp.reset_index()
print(result)

Output:

itemlast_item1count_item1
0ad2
1bc1

This works because the grouped columns are a MultiIndex where each tuple is (original_column_name, aggregation_function). By swapping the tuple elements before joining, we get the aggfunc_colname format you want.

2. Use Pandas Named Aggregation (Most Readable & Maintainable)

For better clarity (especially as your aggregation logic grows), use named aggregation—this lets you define the exact column names you want directly in the agg() call, no post-processing needed:

import pandas as pd
import numpy as np

df = pd.DataFrame({"item":['a','a','a','b'],"item1":['b','d',np.nan,'c']})
df_grp = df.groupby("item").agg(
    last_item1=('item1', 'last'),
    count_item1=('item1', 'count')
).reset_index()
print(df_grp)

Output:

itemlast_item1count_item1
0ad2
1bc1

This method is self-documenting: anyone reading the code immediately knows what each aggregated column represents, and you avoid having to manipulate column names after the fact. It's the recommended approach for modern Pandas (version 0.25+).


内容的提问来源于stack exchange,提问作者william007

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:03:13