Aggregate function to data frame in pandas
<p>I want to create a dataframe from an aggregate function. I thought that it would create by default a dataframe as this solution states, but it creates a series and I don't know why (<a href="http://stackoverflow.com/questions/10373660/converting-a-pandas-groupby-object-to-dataframe">Converting a Pandas GroupBy object to DataFrame</a>).</p>

<p>The dataframe is from Kaggle's San Francisco Salaries. My code:</p>

<pre><code>df=pd.read_csv('Salaries.csv')

in: type(df)
out: pandas.core.frame.DataFrame

in: df.head()
out: EmployeeName   JobTitle    TotalPay    TotalPayBenefits    Year    Status  2BasePay    2OvertimePay    2OtherPay   2Benefits   2Year
0   NATHANIEL FORD  GENERAL MANAGER-METROPOLITAN TRANSIT AUTHORITY  567595.43   567595.43   2011    NaN 167411.18   0.00    400184.25   NaN 2011-01-01
1   GARY JIMENEZ    CAPTAIN III (POLICE DEPARTMENT) 538909.28   538909.28   2011    NaN 155966.02   245131.88   137811.38   NaN 2011-01-01
2   ALBERT PARDINI  CAPTAIN III (POLICE DEPARTMENT) 335279.91   335279.91   2011    NaN 212739.13   106088.18   16452.60    NaN 2011-01-01
3   CHRISTOPHER CHONG   WIRE ROPE CABLE MAINTENANCE MECHANIC    332343.61   332343.61   2011    NaN 77916.00    56120.71    198306.90   NaN 2011-01-01
4   PATRICK GARDNER DEPUTY CHIEF OF DEPARTMENT,(FIRE DEPARTMENT)    326373.19   326373.19   2011    NaN 134401.60   9737.00 182234.59   NaN 2011-01-01

in: df2=df.groupby(['JobTitle'])['TotalPay'].mean()
type(df2)
out: pandas.core.series.Series
</code></pre>

<p>I want df2 to be a dataframe with the columns 'JobTitle' and 'TotalPlay'</p>

<p>Breaking down your code:</p>

<pre><code>df2 = df.groupby(['JobTitle'])['TotalPay'].mean()
</code></pre>

<p>The <code>groupby</code> is fine.  It's the <code>['TotalPay']</code> that is the misstep.  That is telling the <code>groupby</code> to only execute the the <code>mean</code> function on the <code>pd.Series</code> <code>df['TotalPay']</code> for each group defined in <code>['JobTitle']</code>.  Instead, you want to refer to this column with <code>[['TotalPay']]</code>.  Notice the double brackets.  Those double brackets say <code>pd.DataFrame</code>.</p>

<hr>

<h3>Recap</h3>

<pre><code>df2 = df2=df.groupby(['JobTitle'])[['TotalPay']].mean()
</code></pre>

python pandas dataframe aggregate-functions series