首页 > 解决方案 > Numpy / Pandas:从列表中随机选择 n 个项目,其中 n 是随机整数,对于每个索引

问题描述

我是 numpy 和 pandas 的新手,我正在尝试编写这段代码来创建一个 pandas 系列。对于系列中的每个索引,我想从上面的列表中随机选择一个随机数量的兴趣,在这种情况下为 1 - 3,没有重复。如果可能的话,我想找到改进我的代码的方法。

谢谢

def random_interests(num):
    interests = [1, 2, 3, 4, 5, 6]
    stu_interests = []
    for n in range(num):
        stu_interests.append(np.random.choice(interests, np.random.randint(1, 4), replace=False))
    rand_interests = pd.Series(stu_interests)

标签: pythonpandasnumpyrandomseries

解决方案


您必须在函数中添加一个返回值,以便从中获得结果。通过在底部添加返回,您的代码将是:

def random_interests(num):
    interests = [1, 2, 3, 4, 5, 6]
    stu_interests = []
    for n in range(num):
        stu_interests.append(np.random.choice(interests, np.random.randint(1, 4), replace=False))
    rand_interests = pd.Series(stu_interests)
    return rand_interests

通过运行 n=5 输出是:

random_interests(5)

0    [5, 6, 4]
1          [5]
2    [1, 6, 4]
3    [3, 4, 1]
4       [1, 2]
dtype: object

推荐阅读