How can I add only the first elements of an array in python?

Viewed 819

If I have an array, for example: a = np.array([[1,2], [2,5], [4,8]]), where the first digit represents the x value and the second one represents the y value, how can I add all of the first digits (x values) and all of the second digits (y values). The output should look something like this: 7, 15 Thanks!

4 Answers
x, y = a[:,0].sum(), a[:,1].sum()

You can use numpy sum() for row axis (axis = 0). This sum the values in the same location of each row, or other way to say, it sums the values in the same column.

import numpy as np
a = np.array([[1,2], [2,5], [4,8]])
print(np.sum(a,axis=0))

Use numpy built-ins

np.sum(a,axis=0)
a = np.array([[1,2], [2,5], [4,8]])
x = 0
y = 0
for element in a:
    x += element[0]
    y += element[1]
print("x: " + str(x))
print("y: " + str(y))

Output:

>> x: 7
>> y: 15

Access each element of the array and then for each element take first element as x and second as y

Related