2

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.

2 Answers 2

2

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 ]]
Sign up to request clarification or add additional context in comments.

Comments

0

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 ]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.