Pandas分组聚合后自定义列名格式(将item1_last转为last_item1)的更优实现方法咨询
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:
| item | last_item1 | count_item1 | |
|---|---|---|---|
| 0 | a | d | 2 |
| 1 | b | c | 1 |
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:
| item | last_item1 | count_item1 | |
|---|---|---|---|
| 0 | a | d | 2 |
| 1 | b | c | 1 |
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

