Pandas groupby返回Series而非DataFrame及列名缺失问题求助
Hey there! Let's tackle your Pandas groupby issue head-on—this is a super common gotcha, so you're not alone.
Why You're Getting a Series Instead of a DataFrame
When you run new_df = df_ncis.groupby(['state', 'year'])['totals'].mean(), Pandas returns a Series because you're aggregating a single column (totals). The state and year become a multi-level index for the Series, and the aggregated mean values are the Series' data points. This is Pandas' default behavior for single-column aggregations to keep output concise.
Solutions to Get a DataFrame & Fix the Missing Column Name
Here are three straightforward ways to resolve both issues:
Use
as_index=Falseingroupby
This tells Pandas to keepstateandyearas regular columns instead of setting them as the index, and returns a DataFrame directly. Your aggregated column will retain the original name (totals):new_df = df_ncis.groupby(['state', 'year'], as_index=False)['totals'].mean()Call
reset_index()on the Series
Convert the multi-level index of the resulting Series into regular columns. This will turn the Series into a DataFrame, with the aggregated values in a column namedtotals:new_df = df_ncis.groupby(['state', 'year'])['totals'].mean().reset_index()Use
agg()to define a custom column name
If you want to rename the aggregated column to something more descriptive (likeaverage_totals), use theagg()method. This also returns a DataFrame by default, and you can still reset the index if needed:# Returns a DataFrame with index as state/year, and column 'average_totals' new_df = df_ncis.groupby(['state', 'year']).agg(average_totals=('totals', 'mean')) # Optional: Reset index to make state/year regular columns new_df = new_df.reset_index()
All these methods will give you the DataFrame structure you're expecting, while fixing the "missing column name" issue either by retaining the original name or letting you define a custom one.
内容的提问来源于stack exchange,提问作者Angry Physicist

