Mean of values in a column for unique values in another column (Python)
<p>I am using Python 2.7 (Anaconda) for processing tabular data. I have loaded a textfile with two columns, e.g. </p>

<pre><code>[[ 1.  8.]
 [ 2.  4.]
 [ 3.  1.]
 [ 4.  5.]
 [ 5.  6.]
 [ 1.  9.]
 [ 2.  0.]
 [ 3.  7.]
 [ 4.  3.]
 [ 5.  2.]]
</code></pre>

<p>my goal is to calculate the mean over all values in the second column which match the unique values in the first one, e.g. the mean value for 1 would be 8.5, for 2 it would be two, for 3 it would be 4. 
First, I filtered out the unique values in the first column by extracting the column and applying np.unique() resulting in the array "unique". I created a loop that works when I define the unique value:</p>

<pre><code>mean= 0
values=[]
for i in range(0,len(first),1):
    if first[i]==1:
        values.append(second[i])
print(np.mean(values))
</code></pre>

<p>where first and second are the specific columns.
Now I want to make this not so specific. I tried</p>

<pre><code>mean = 0
values = []
means=[]

for i in unique:
    for k in range(0,len(first),1):
        if first[k]==i:
            values.append(second[k])
            mean = np.mean(values)
            means.append(mean)
    mean=0
    values=[]
print(means)
</code></pre>

<p>but it only returns the original second column.
Does anybody have an idea on how to make this code non-specific? In reality, I have about 70k rows, so I cannot do it mannually.
Thanks and regards,
Maurus</p>

<p>In pandas, you can achieve this by using <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html" rel="nofollow">groupby</a>:</p>

<pre><code>In [97]: data
Out[97]: 
array([[ 1.,  8.],
       [ 2.,  4.],
       [ 3.,  1.],
       [ 4.,  5.],
       [ 5.,  6.],
       [ 1.,  9.],
       [ 2.,  0.],
       [ 3.,  7.],
       [ 4.,  3.],
       [ 5.,  2.]])

In [98]: import pandas as pd

In [99]: df = pd.DataFrame(data, columns=['first', 'second'])

In [100]: df.groupby('first').mean().reset_index()
Out[100]: 
   first  second
0    1.0     8.5
1    2.0     2.0
2    3.0     4.0
3    4.0     4.0
4    5.0     4.0
</code></pre>

python mean tabular-data