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

Time:08-08

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]

CodePudding user response:

Try using:

row_array = arr.sum(0)

To calculate the sum of the columns

Instead of:

row_array = sum(array[0,:])
  • Related