gpt4 book ai didi

python - 从列表中创建随机分组

转载 作者:行者123 更新时间:2023-12-01 07:40:38 30 4
gpt4 key购买 nike

我需要列出 500 多人的名单,并将他们分成 15 人一组。这些组应该随机,这样我们就不会得到每个人的姓氏都以“开头的组” B”,例如。但我还需要平衡 15 人的小组,以尽可能实现性别平等。该列表位于“students.csv”文件中,其结构如下:


Last, First, ID, Sport, Gender, INT
James, Frank, f99087, FOOT, m, I
Smith, Sally, f88329, SOC, f,
Cranston, Bill, f64928, ,m,

我一直在寻找 pandas 的某种解决方案,但我的编码知识有限。到目前为止,我得到的代码只是对数据进行了一些探索。

import pandas as pd
data = pd.read_csv('students.csv', index_col='ID')
print(data)

print(data.Gender.value_counts())

最佳答案

我要做的第一件事就是过滤成两个列表,每个列表对应一个性别:

males = [d for d in data if d.Gender == 'm']
females = [d for d in data if d.Gender == 'f']

接下来,打乱列表的顺序,以便更容易“随机”选择,而实际上不必选择随机索引:

random.shuffle(males)
random.shuffle(females)

然后,选择元素,同时尝试或多或少与性别比例保持一致:

# establish number of groups, and size of each group
GROUP_SIZE = 15
GROUP_NUM = math.ceil(len(data) / group_size)
# make an empty list of groups to add each group to
groups = []
while len(groups) < GROUP_NUM and (len(males) > 0 and len(females) > 0):
# calculate the proper gender ratio, to perfectly balance this group
num_males = len(males) / len(data) * GROUP_SIZE
num_females = GROUP_SIZE - num_males
# select that many people from the previously-shuffled lists
males_in_this_group = [males.pop(0) for n in range(num_males) if len(males) > 0]
females_in_this_group = [males.pop(0) for n in range(num_females) if len(females) > 0]
# put those two subsets together, shuffle to make it feel more random, and add this group
this_group = males_in_this_group + females_in_this_group
random.shuffle(this_group)
groups.append(this_group)

这将确保每组中的性别比例尽可能真实地反射(reflect)原始样本。当然,最后一组将比其他组小,并且将包含其他组中的“剩余内容”。

关于python - 从列表中创建随机分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56737497/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com