pandas - agg() function
<p>The ordering of my age, height and weight columns is changing with each run of the code.  I need to keep the order of my agg columns static because I ultimately refer to this output file according to the column locations.  What can I do to make sure age, height and weight are output in the same order every time?</p>

<pre><code>d = pd.read_csv(input_file, na_values=[''])
df = pd.DataFrame(d)
df.index_col = ['name', 'address']

df_out = df.groupby(df.index_col).agg({'age':np.mean, 'height':np.sum, 'weight':np.sum})
df_out.to_csv(output_file, sep=',')
</code></pre>

<p>I think you can use subset:</p>

<pre><code>df_out = df.groupby(df.index_col)
           .agg({'age':np.mean, 'height':np.sum, 'weight':np.sum})[['age','height','weight']]
</code></pre>

<p>Also you can use <code>pandas</code> functions:</p>

<pre><code>df_out = df.groupby(df.index_col)
           .agg({'age':'mean', 'height':sum, 'weight':sum})[['age','height','weight']]
</code></pre>

<p>Sample:</p>

<pre><code>df = pd.DataFrame({'name':['q','q','a','a'],
                   'address':['a','a','s','s'],
                   'age':[7,8,9,10],
                   'height':[1,3,5,7],
                   'weight':[5,3,6,8]})

print (df)
  address  age  height name  weight
0       a    7       1    q       5
1       a    8       3    q       3
2       s    9       5    a       6
3       s   10       7    a       8
df.index_col = ['name', 'address']
df_out = df.groupby(df.index_col)
           .agg({'age':'mean', 'height':sum, 'weight':sum})[['age','height','weight']]

print (df_out)
              age  height  weight
name address                     
a    s        9.5      12      14
q    a        7.5       4       8
</code></pre>

python pandas format