我在尝试使用 NumPy 计算学生的平均分数时遇到问题。我编写的代码出现以下错误:
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
代码
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)
这是“grades.csv”文件中我的数据:
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
我尝试过的 我尝试加载数据、过滤数字列并使用 np.nanmean() 计算平均分数。我还确保适本地处理缺失值。
期望 我希望代码能够毫无错误地计算并打印每个学生的平均分数。
请求帮助 如果您能帮助我了解错误原因以及解决方法,我将不胜感激。
最佳答案
函数np.nanmean()
是正确的,因为它 ignores the NaN values, read documentation.
对于您的示例,您的数字列是异构(多类型)数组。您可以通过使用 array.astype() 函数将其转换为同构(单一类型)数组来解决此问题。
关于python - 使用 NumPy 计算平均分数时出错 : 'ufunc add' did not contain a loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77327743/