使用 NumPy 计算平均分数时出错:“ufunc add”不包含循环

问题描述 投票:0回答:1

我在尝试使用 NumPy 计算学生的平均分数时遇到问题。我编写的代码出现以下错误:

回溯(最近一次调用最后一次): 平均分数 = np.nanmean(numeric_columns, axis=1) ... numpy.core._exceptions._UFuncNoLoopError:ufunc“add”不包含具有签名匹配类型的循环

代码

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() 计算平均分数。我还确保适当处理缺失值。

期望 我希望代码能够毫无错误地计算并打印每个学生的平均分数。

请求帮助 如果您能帮助我了解错误原因以及解决方法,我将不胜感激。

python numpy error-handling average numpy-ufunc
1个回答
0
投票

你可以使用熊猫吗?

重新创建一个简单的示例:

然后您只需使用

.mean(axis = 1)
功能即可。

df['student_avg'] = df.mean(axis = 1)

© www.soinside.com 2019 - 2024. All rights reserved.