Two dimensional Arrays: Calculating the sum across the rows and down the columns

Question:

I’m attempting to calculate the sum across the rows and down the columns. I’ve generated the randomization and rearranged the values. Here is a reproducible example.

import numpy as np 
import pandas as pd

# Generate randomized numbers 
np.random.seed(101)
array = np.random.randint(50, size = 20)
print(array)

# Arrange columns 
arr = array.reshape(5, 4).T
columns = arr[0, :].astype(str)
data = arr[0:].astype(float)
df = pd.DataFrame(data, columns=columns)
print(df)

#Calculate the sum of the rows 
row = arr
row_array = row.sum(1)
print(row_array)

This is what I get when I run the command. I’m needing to generate a 2-dimensional array, not 1.

[31 11 17  6 23 11 47  9 13 40  4 40 28  0 46  5 12 29 40 49]
31.0  23.0  13.0  28.0  12.0
0  31.0  23.0  13.0  28.0  12.0
1  11.0  11.0  40.0   0.0  29.0
2  17.0  47.0   4.0  46.0  40.0
3   6.0   9.0  40.0   5.0  49.0
[107  91 154 109]
Asked By: Victoria

||

Answers:

Try using:

row_array = arr.sum(0)

To calculate the sum of the columns

Instead of:

row_array = sum(array[0,:])
Answered By: MOHAMED HABI
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.