bertington313
bertington313

Reputation: 49

computing average and appending to new array numpy

I need to compute and average of specific array and create a new one that is concatenated with another array. Lets say my array is following :

[[99 73 97 98]
 [98 71 70 99]]

and I've got another array : ['1' '2']

so basically what I need is : [[1. 2.] [91.75 84.5]]

in other words the first line is just the second array , and second is the average of each element of the

[[99 73 97 98]
 [98 71 70 99]]

array respectively.

(if it helps , I've got a csv file : )

student_id, 521, 597, 624, 100, 
1, 99, 73, 97, 98, 
2, 98, 71, 70, 99,

student_id line is id of student, in every other line first number is the exercise number and the rest are grades. I need to create an array that contains exercises numbers and the average grades of each.

I understand that it is possible to do so with the vstack method, but I need to do so without using loops.

Upvotes: 2

Views: 747

Answers (2)

jpp
jpp

Reputation: 164613

You can use Pandas, which simplifies reading structured data from CSV files:

import pandas as pd
from io import StringIO

x = """student_id, 521, 597, 624, 100
1, 99, 73, 97, 98
2, 98, 71, 70, 99
"""

# replace StringIO(x) with 'file.csv'
df = pd.read_csv(StringIO(x))

# calculate mean by row
df['mean'] = df.iloc[:, 1:].mean(1)

# select columns and transpose
res = df[['student_id', 'mean']].values.T

# array([[  1.  ,   2.  ],
#        [ 91.75,  84.5 ]])

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61900

Use mean and then vstack:

import numpy as np

ids = np.array([1, 2])  # this is just array2
arr = np.array([[99, 73, 97, 98],
          [98, 71, 70, 99]])
result = np.vstack((ids, np.mean(arr, axis=1)))
print(result)

Output

[[ 1.    2.  ]
 [91.75 84.5 ]]

Upvotes: 2

Related Questions