BaRud
BaRud

Reputation: 3218

Summing all even and odd columns separately in a numpy array

I have a numpy array like this:

<class 'numpy.ndarray'>
[[-18.29750213   0.1          -0.1         0.4          -0.8        ]
 [-18.20350213   0.7          -0.2         0.1          -0.3        ]
 [-18.11050213   0.5          -0.6         0.2          -0.1        ]
 ..., 
 [  9.49249787   0.5          -0.6         0.2          -0.2        ]
 [  9.58649787   0.3          -0.3         0.7          -0.8        ]
 [  9.67949787   0.2          -0.6         0.5          -0.1        ]]

I am trying to add all even and odd column separately for each row, i.e., at the end I am looking to get a table like:

-18.29750213 0.5(i.e. 0.1+0.4) -0.9(i.e. -.1-.8)
-18.20350213 0.8(i.e. 0.7+0.1) -0.5(i.e. -.2-.3)
-18.11050213 0.7(i.e. 0.5+0.2) -0.7(i.e. -.6-.1)
...

while I can separate the colums as lines[:,::2] and lines[:,1::2] I can add them, i.e. sum(lines[:2,::2]) and sum(lines[:,1::2]) is now working:

d_dn = sum(lines[:,::2])
d_up = sum(lines[:,1::2])
print(lines[:,0].size)
print(d_dn.size)
print(d_up.size)

is giving:

301
10
9

Upvotes: 1

Views: 2294

Answers (1)

cs95
cs95

Reputation: 402333

Just call np.sum and pass an axis argument. Afterwards, column_stack the pieces together.

i = arr[:, [0]]
j = arr[:, 1::2].sum(1)
k = arr[:, 2::2].sum(1)

np.column_stack((i, j, k))

array([[-18.29750213,   0.5       ,  -0.9       ],
       [-18.20350213,   0.8       ,  -0.5       ],
       [-18.11050213,   0.7       ,  -0.7       ],
       [  9.49249787,   0.7       ,  -0.8       ],
       [  9.58649787,   1.        ,  -1.1       ],
       [  9.67949787,   0.7       ,  -0.7       ]])

Upvotes: 1

Related Questions