Andre_k
Andre_k

Reputation: 1740

Summing elements of numpy array in Python

I have an numpy array

>>> clf_prob.dtype()

array([[ 0.05811791,  0.06526527,  0.06024136, ...,  0.06972481],
       [ 0.06093686,  0.06357167,  0.06462331, ...,  0.06999094],
       [ 0.08188396,  0.08504034,  0.0820972 , ...,  0.08487802],
       [ 0.05197106,  0.0786195 ,  0.15669477, ...,  0.0893244]])

I'm trying to add elements of these arrays such that my output would be:

[[0.05811791 + 0.06526527 + 0.06024136 +...+ 0.06972481],
[0.06093686 + 0.06357167 + 0.06462331 +...+0.06999094],
[0.08188396 + 0.08504034 + 0.0820972 + ...+  0.08487802],
[0.05197106 + 0.0786195  + 0.15669477+ ...+ 0.0893244]]

I tried doing

sum(map(sum, clf_prob))

This doesn't gives me desired output. Any suggestion?

Upvotes: 0

Views: 1936

Answers (3)

Code Pope
Code Pope

Reputation: 5459

Another probability is to use ufunc of numpy:
np.sum.reduce(clf_prob)
which will give the sum over the first axis. You can also use the axis parameter to sum over another axis.

Upvotes: 0

Isdj
Isdj

Reputation: 1856

numpy.sum() over your intended axis (1) should do the job in your case

Upvotes: 0

Mathias711
Mathias711

Reputation: 6668

You can do

clf_prob.sum(axis=1)

This will take the sum over a certain axis, in this case rows.

Upvotes: 2

Related Questions