I'm encountering an issue when trying to calculate the average scores of students using NumPy. The code I've written is giving me the following error:
Traceback (most recent call last): average_scores = np.nanmean(numeric_columns, axis=1) ... numpy.core._exceptions._UFuncNoLoopError: ufunc 'add' did not contain a loop with signature matching types
CODE
import numpy as np
# Defining anything that could be missing in someone else's data
missing_values = ['N/A', 'NA', 'nan', 'NaN', 'NULL', '', '']
# Defining each of the data types
dtype = [('Student Name', 'U50'), ('Math', 'float'),
('Science', 'float'), ('English', 'float'),
('History', 'float'), ('Art', 'float')]
# Load data into a numpy array
data = np.genfromtxt('grades.csv', delimiter=',',
names=True, dtype=dtype,
encoding=None, missing_values=missing_values,
filling_values=np.nan, ndmin=2)
# Get all the field names (column names) in the structured array
field_names = data.dtype.names
# Extract the numeric columns by checking their data type
numeric_columns = data[[field for field in field_names if data[field].dtype == float]]
# Calculate the average score for each student
average_scores = np.nanmean(numeric_columns, axis=1)
print(average_scores)
Here is my data in the 'grades.csv' file:
Student Name,Math,Science,English,History,Art
Alice,90,88,94,85,78
Bob, 85,92,,88,90
Charlie,78,80,85,85,79
David,94,,90,92,84
Eve,92,88,92,90,88
Frank,,95,94,86,95
What I've Tried I've tried loading the data, filtering the numeric columns, and calculating the average scores using np.nanmean(). I've also made sure to handle missing values appropriately.
EXPECTATIONS I expected the code to calculate and print the average scores for each student without errors.
REQUEST FOR HELP I'd appreciate any assistance in understanding the cause of the error and how to resolve it.
The function
np.nanmean()
is correct as it ignores the NaN values, read documentation.For your example, your numeric columns is a heterogeneous (multi-type) array. You can resolve this by converting it to a homogeneous (single-type) array with the
array.astype()
function.Try this: