NUMPY: AVERAGE OF ROWS | Sololearn: Learn to code for FREE!

+1

NUMPY: AVERAGE OF ROWS

''' In a matrix, or 2-d array X, the averages (or means) of the elements of rows is called row means. Task Given a 2D array, return the rowmeans. Input Format First line: two integers separated by spaces, the first indicates the rows of matrix X (n) and the second indicates the columns of X (p) Next n lines: values of the row in X Output Format An numpy 1d array of values rounded to the second decimal. 2 2 1.5 1 2 2.9 Sample Output [1.25 2.45] ''' n, p = [int(x) for x in input().split()] list = [] new_list = [] for i in range (n): list.append(input().split()) import numpy as np arr = np.array(list) mean = arr.mean(axis = 1) print (mean) #This code generates error as input data is a string. Explain ways to convert all strings into int/float before appending it to list or to change the data type of all the items in an array.

1/3/2021 12:31:51 PM

CHANDAN ROY

9 Answers

New Answer

+6

n, p = [int(x) for x in input().split()] list = [] for i in range(n): list.append([float(j) for j in input().split()]) import numpy as np arr = np.array(list, dtype='f') mean = arr.mean(axis=1) print(mean.round(2))

+4

#Solution - import numpy as np rows, columns = [int(x) for x in input().split()] matrix = [] for row in range(rows): matrix.append(input().split()) matrix = list(np.float_(matrix)) #print(matrix) average = np.average(matrix, axis=1) print(average.round(2))

+2

Working 5/5: n, p = [int(x) for x in input().split()] l=list() for i in range(n): l.append([float(j) for j in input().split()]) import numpy as np arr=np.array(l) arrz=arr.reshape(n,p) mn=np.mean(arrz,axis=1) print(np.round(mn,decimals=2)) Any queries feel free to dm

+1

CHANDAN ROY Sent solution in DM.

+1

# Try this: n, p = [int(x) for x in input().split()] list = [] for i in range (n): list.append([float(j) for j in input().split()]) import numpy as np arr = np.array(list) mean = arr.mean(axis = 1) print (mean) # Update me if it still not solved. Thanks!!

0

I Am AJ ! Rafique Sir, help!!

0

Task Given a 2D array feature matrix X and a vector y, return the coefficient vector; see the formula. First line: two integers separated by spaces, the first indicates the rows of the feature matrix X (n) and the second indicates the columns of X (p) Next n lines: values of the row in the feature matrix Last line: p values of target y MY CODE import numpy as np rows, columns = [int(x) for x in input().split()] matrix = [] for row in range(rows): matrix.append(input().split()) matrix = list(np.float_(matrix)) #print(matrix) average = np.average(matrix, axis=1) print(average.round(2)) Error: Not satisfied any Test case

0

import numpy as np arr = np.array([input().split() for x in range(n)]).astype(float) mean = arr.mean(axis=1).round(2) print(mean)

0

import numpy as np arr=np.array([[1.5,1],[2,2.9]]) print(arr.mean(axis=1))