Pandas groupby to get two aggregated functions then convert to list of list
<p>I'm looking for a better way to write this. This works fine for my sample data set, but is pretty slow on a larger data set. Starting with a <code>dataframe</code> of customer purchases numbers. I'd like to get a list of lists in the format: ``[Customer, Mean of Orders, Count of Orders]`</p>

<pre><code>import pandas as pd

df = pd.DataFrame(data = [['Customer0', 10], ['Customer0', 12], ['Customer1', 23]],
                  columns=['Customer', 'Orders'])

grouped = df.groupby(['Customer']).mean()
grouped['count'] =  df.groupby(['Customer']).count()

values = grouped.values.tolist()
indexes = grouped.index.tolist()

for x in range(0,len(values)):
    values[x].insert(0, indexes[x])

print values
</code></pre>

<p>Output:</p>

<pre><code>[['Customer0', 11, 2], ['Customer0', 23, 1]]
</code></pre>

<p>Can you try this one? </p>

<pre><code>df.groupby('Customer').agg(['mean', 'count']).reset_index().values.tolist()
Out: [['Customer0', 11, 2], ['Customer1', 23, 1]]
</code></pre>

<p>A small note: This can only improve your code significantly if the number of groups (<code>len(values)</code>) is quite large because we are not looping here. If you have only a small number of groups, I guess the improvement would be 2x at most.  </p>

python python-2.7 pandas