Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum rows where value equal in column

How can I sum across rows that have equal values in the first column of a numpy array? For example:

In: np.array([[1,2,3],
             [1,4,6], 
             [2,3,5],
             [2,6,2],
             [3,4,8]])

Out: [[1,6,9], [2,9,7], [3,4,8]]

Any help would be greatly appreciated.

like image 427
user998476 Avatar asked May 04 '15 22:05

user998476


People also ask

How do you sum columns based on conditional of other column values?

Basically, the SUMIFS function is designed to add up a column of numbers, but, include only those rows that meet one or more conditions. Each condition is defined by a pair of arguments. Here is the basic syntax: =SUMIFS(sum_range, criteria_range1, criteria1, ...)

How do I sum a specific value in a column in pandas?

Pandas DataFrame sum() MethodThe sum() method adds all values in each column and returns the sum for each column. By specifying the column axis ( axis='columns' ), the sum() method searches column-wise and returns the sum of each row.


2 Answers

Pandas has a very very powerful groupby function which makes this very simple.

import pandas as pd

n = np.array([[1,2,3],
             [1,4,6], 
             [2,3,5],
             [2,6,2],
             [3,4,8]])

df = pd.DataFrame(n, columns = ["First Col", "Second Col", "Third Col"])

df.groupby("First Col").sum()
like image 73
canyon289 Avatar answered Sep 20 '22 04:09

canyon289


Approach #1

Here's something in a numpythonic vectorized way based on np.bincount -

# Initial setup             
N = A.shape[1]-1
unqA1, id = np.unique(A[:, 0], return_inverse=True)

# Create subscripts and accumulate with bincount for tagged summations
subs = np.arange(N)*(id.max()+1) + id[:,None]
sums = np.bincount( subs.ravel(), weights=A[:,1:].ravel() )

# Append the unique elements from first column to get final output
out = np.append(unqA1[:,None],sums.reshape(N,-1).T,1)

Sample input, output -

In [66]: A
Out[66]: 
array([[1, 2, 3],
       [1, 4, 6],
       [2, 3, 5],
       [2, 6, 2],
       [7, 2, 1],
       [2, 0, 3]])

In [67]: out
Out[67]: 
array([[  1.,   6.,   9.],
       [  2.,   9.,  10.],
       [  7.,   2.,   1.]])

Approach #2

Here's another based on np.cumsum and np.diff -

# Sort A based on first column
sA = A[np.argsort(A[:,0]),:]

# Row mask of where each group ends
row_mask = np.append(np.diff(sA[:,0],axis=0)!=0,[True])

# Get cummulative summations and then DIFF to get summations for each group
cumsum_grps = sA.cumsum(0)[row_mask,1:]
sum_grps = np.diff(cumsum_grps,axis=0)

# Concatenate the first unique row with its counts
counts = np.concatenate((cumsum_grps[0,:][None],sum_grps),axis=0)

# Concatenate the first column of the input array for final output
out = np.concatenate((sA[row_mask,0][:,None],counts),axis=1)

Benchmarking

Here's some runtime tests for the numpy based approaches presented so far for the question -

In [319]: A = np.random.randint(0,1000,(100000,10))

In [320]: %timeit cumsum_diff(A)
100 loops, best of 3: 12.1 ms per loop

In [321]: %timeit bincount(A)
10 loops, best of 3: 21.4 ms per loop

In [322]: %timeit add_at(A)
10 loops, best of 3: 60.4 ms per loop

In [323]: A = np.random.randint(0,1000,(100000,20))

In [324]: %timeit cumsum_diff(A)
10 loops, best of 3: 32.1 ms per loop

In [325]: %timeit bincount(A)
10 loops, best of 3: 32.3 ms per loop

In [326]: %timeit add_at(A)
10 loops, best of 3: 113 ms per loop

Seems like Approach #2: cumsum + diff is performing quite well.

like image 28
Divakar Avatar answered Sep 20 '22 04:09

Divakar