【问题标题】:Numpy / Pandas: randomly choose n items from a list, for where n is a random integer, for each index [closed]Numpy / Pandas:从列表中随机选择 n 个项目,其中 n 是随机整数,对于每个索引 [关闭]
【发布时间】:2020-10-07 18:32:36
【问题描述】:

我是 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)

【问题讨论】:

  • 您的解决方案有效吗?如果不是,那它是如何不足的?
  • 它确实有效,但我只是想学习改进它的方法,因为我是 numpy / pandas 的新手
  • 我投票结束这个问题,因为它是工作代码并且 OP 正在寻找替代方案。欢迎来到 SO。这不是讨论论坛或教程。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。
  • 如果您的解决方案确实有效,请拨打CodeReview Tour 并访问其Help Center,看看您的问题是否与那边的主题相关。

标签: python pandas numpy random series


【解决方案1】:

这是一种方法。使用更快的 apply 可以避免 for 循环。此外,您无需创建单独的变量stu_interests,当num 较高时会消耗更多内存

def random_interests(num):
    interests = [1, 2, 3, 4, 5, 6]
    rand_interests = pd.DataFrame(np.nan, index=[x for x in range(num)], columns=['random_list'])
    rand_interests['random_list'] =  rand_interests['random_list'].apply(lambda x: np.random.choice(interests, np.random.randint(1, 4), replace=False))
    return rand_interests['random_list']
 

【讨论】:

    【解决方案2】:

    你必须在你的函数中添加一个返回值,这样你才能从中得到一个结果。通过在底部添加返回,您的代码将是:

    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
    

    【讨论】:

    • 谢谢!我省略了最后的返回以使事情更短,所以你认为代码是好的吗?
    • 是的,完美
    【解决方案3】:

    或者单排

    pd.Series([np.random.choice(
        [1, 2, 3, 4, 5, 6], np.random.randint(1, 4), replace=False)
               for i in range(num)])
    

    输出:

    0       [3, 6]
    1    [4, 2, 1]
    2       [6, 5]
    3          [3]
    

    【讨论】:

    • 好.. 我很欣赏单行的令人惊叹的因素。但是,您是否认为将列表 [1, 2,3, 4, 5, 6] 存储在变量中会更好,因为它会被重用?
    • 是的,如果您要重用[1, 2,3, 4, 5, 6],那么最好将其存储在一个变量中,并在单行中使用相同的变量(就像变量 num 一样)
    猜你喜欢
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2019-12-02
    • 2017-01-26
    相关资源
    最近更新 更多