Matrix: Sum of a column
AnsweredHello everyone,
I'm new to Python and could need your help.
I would like to sum up a column in a matrix.
My matrix is defined with pandas:
cities = [1,2,3,4,5]
seq = [[0, 3, 0, 5, 0], [1, 2, 3, 0, 0], [0, 1, 5, 0, 2], [0, 3, 1, 0, 0], [0, 9, 0, 1, 0]]
matrix = pd.DataFrame(seq, columns=cities, index=cities)
print(matrix, '\n')
which gives:
1 2 3 4 5 1 0 3 0 5 0 2 1 2 3 0 0 3 0 1 5 0 2 4 0 3 1 0 0 5 0 9 0 1 0
In the next step I have to formulate constrains for which I need the sum of row i and/or column j.
I tried it like this:
column = (sum(matrix[i][:] for i in cities ))
row = (sum(matrix[:][i] for i in cities ))
Unfortunately, both give this result and sum up the rows but not the columns.
1 8 2 6 3 8 4 4 5 10 dtype: int64
I found, that there is the following possibility, but I only want to sum up column i in my constraint and not all.
matrix.sum(axis = 0) #columns
matrix.sum(axis = 1) #rows
Best regards
Marc
-
Hi Marc,
Your last attempt is correct.
The code
number = matrix.sum(axis=0)
print(number)provides
1 1
2 18
3 9
4 6
5 2
dtype: int64, i.e., the sum of each column saved as a \(\texttt{pandas Series}\). You can access the value of the sum of the second column via
print(number[2])
which prints
18
The index of the columns is defined via your list \(\texttt{cities}\).
It works the same for rows.Best regards,
Jaromił0 -
Hi Jaromił,
thanks for the explanation and solution! It works :)
0
Please sign in to leave a comment.
Comments
2 comments