【问题标题】:Randomly sampling from multiple lists从多个列表中随机抽样
【发布时间】:2020-12-07 13:31:43
【问题描述】:

我有一些数据目前存储在 3 个列表中,我们称它们为 a、b 和 c。这些列表都包含n 元素。我想随机抽取我的数据样本,比如大小sample_n,以创建一些较小的数据集来玩,但我想从每个列表中抽取相同的随机样本。也就是说,我想从每个列表中随机选择相同的元素。因此,如果我随机选择元素i,我想从每个列表(a[i]、b[i] 和c[i])中获取元素i。我不想生成 3 组随机数,以使三个列表的元素不匹配。例如,为每组单独运行 this random sampling 不是我想要的。

我认为我需要做的就是生成一个单独的随机数列表random_list,长度为sample_n,然后执行类似的操作

for element in range(len(random_list)):
      sample_a[element] = a[random_list[element]]
      sample_b[element] = b[random_list[element]]
      sample_c[element] = c[random_list[element]]

但是,我不知道如何生成随机数列表!而且我想知道是否有比我在这里想的更有效的方法。

【问题讨论】:

    标签: python python-3.x numpy random


    【解决方案1】:

    您可以对索引进行洗牌。第一种方式:

    import numpy as np
    indices = list(range(20))
    np.random.shuffle(indices)
    indices
    [9, 13, 0, 19, 17, 10, 14, 5, 7, 18, 8, 3, 16, 4, 15, 11, 12, 6, 1, 2]
    

    第二种方式:

    import random
    indices = list(range(20))
    random.shuffle(indices)
    indices
    [5, 3, 11, 7, 19, 12, 0, 13, 2, 4, 10, 18, 1, 16, 17, 14, 8, 6, 9, 15]
    

    或者,如果索引可以重复:

    np.random.randint(1,5, size=20)
    array([1, 2, 3, 4, 3, 3, 4, 3, 1, 4, 2, 3, 4, 2, 3, 2, 1, 4, 1, 3])
    

    效率。将sample_a、sample_b、sample_c 存储在二维数组中会更快:

    X = np.array([['a','b','c'], ['d','e','f'], ['g','h','i'], ['j','k','l'], ['m','n','o'], ['p', 'q','r'], ['s', 't', 'u']])
    idx = np.random.randint(0, len(X), size=7)
    

    然后使用X[idx,0]、X[idx,1]、X[idx,2] 访问其列

    【讨论】:

    • 谢谢!我认为第三种选择是我要去的。我的代码现在是:sample_n = 1000data = np.column_stack((a, b, c))idx = np.random.randint(0, len(a), size = sample_n)idx = np.reshape(idx, (sample_size, 1))#Force 1D 矢量最终愚蠢的问题(至少在这个主题上)。我现在正在努力将此 sample_data 复制到一个新数组中。我试过:for element in range(len(idx)):sample_data[idx[element], :] = data[idx[element], :] 但得到错误“列表索引必须是整数或切片,而不是元组”。有任何想法吗?抱歉格式化!
    • 重塑是不必要的。你可以使用sample_data[idx,:]=data[idx,:]
    • 谢谢@mathfux,很高兴知道我的 Python 编码目前非常不优雅。我仍然遇到错误,但我相信我在大约一周前遇到了同样的错误(由于某种原因,它没有将 idx 元素称为整数值)所以希望我可以从过去的错误中吸取教训并解决这个问题!
    【解决方案2】:

    对不起,之前搜索过,没有找到任何东西,我刚刚找到了这个:

    Random sample of paired lists in Python

    【讨论】:

    • 请注意,在 numpy 中,您应该选择 zip 而不是 np.column_stack 或类似的东西
    • 谢谢亚当。我也会调查一下。我遇到过它,但使用zip 有点害怕。这似乎是一个相当强大的命令。
    猜你喜欢
    • 1970-01-01
    • 2013-04-13
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多