以下是一个示例代码,演示如何按照区间和条件对数据进行分组。
假设有一个包含学生成绩的数据集,我们希望根据成绩的范围将学生分为不同的组。我们将按照以下条件进行分组:
# 创建学生成绩数据集
scores = [85, 92, 78, 88, 95, 66, 72, 79, 60, 54, 90, 82]
# 创建分组范围和条件
groups = [
{'name': '优秀', 'min': 90, 'max': 100},
{'name': '良好', 'min': 80, 'max': 89},
{'name': '中等', 'min': 70, 'max': 79},
{'name': '及格', 'min': 60, 'max': 69},
{'name': '不及格', 'min': 0, 'max': 59}
]
# 创建分组字典,用于存储每个分组的学生
grouped_data = {group['name']: [] for group in groups}
# 根据条件将学生分组
for score in scores:
for group in groups:
if group['min'] <= score <= group['max']:
grouped_data[group['name']].append(score)
break
# 打印每个分组的学生
for group, students in grouped_data.items():
print(group + ':', students)
运行以上代码,输出结果如下:
优秀: [92, 95, 90]
良好: [85, 88, 82]
中等: [78, 72, 79]
及格: [66, 60]
不及格: [54]
以上代码使用一个列表来存储学生的成绩,然后根据每个分组的范围和条件对学生进行迭代,并将符合条件的学生添加到对应的分组中。最后,打印每个分组的学生。
上一篇:按照区间对数据框进行聚合