我有一个从包含学生 ID、姓名和作业 1、2、3 的 csv 文件构建的数据框... csv 文件将作为输入输入,因此值可能会有所不同。如果学生 ID 不唯一,我想打印错误消息列表。下面的代码工作正常,因为 GradesM3.csv 中没有重复项: grades = pd.read_csv('gradesM3.csv',sep=';') duplicates = pd.concat(g for _, g in grades.groupby("StudentID") if len(g) > 1) zipped = zip(duplicates['StudentID']) for student in zipped: print(f'The student ID {student} appears multiple times.')但是,如果我更改 CSV 文件并创建一些重复的学生 ID,则会出现以下错误:ValueError: No objects to concatenate如果有重复,我正在尝试编写一个打印以下内容的代码:The student ID ('s123789',) appears multiple times.The student ID ('s123789',) appears multiple times.The student ID ('s123789',) appears multiple times.如果没有,则如下:There are no duplicates in your file. 我尝试了以下代码: grades = pd.read_csv('gradesM3.csv',sep=';') duplicates = pd.concat(g for _, g in grades.groupby("StudentID") if len(g) > 1) if len(duplicates)>0: zipped = zip(duplicates['StudentID']) for student in zipped: print(f'The student ID {student} appears multiple times.') else: print('The grades are correctly scaled along the 7-point grading system.')但我收到相同的错误消息:ValueError: No objects to concatenate. 在此先感谢您的帮助。
2 回答
慕尼黑5688855
TA贡献1848条经验 获得超2个赞
使用duplicatedpandas的方法更直接的解决方案是这样的
import pandas as pd
# Example data
df = pd.DataFrame({'id' : [1,2,2,4, 5, 1], 'name' : ["a", "b", "b", "d", "e", "a"]})
print(df)
# id name
#0 1 a
#1 2 b
#2 2 b
#3 4 d
#4 5 e
#5 1 a
# Get the duplicates - each df row where th eid column is duplicated
df_duplicates = df[df['id'].duplicated()]
for id in df_duplicates['id']:
print(f"Student {id} is a duplicate")
#Student 2 is a duplicate
#Student 1 is a duplicate
添加回答
举报
0/150
提交
取消