【问题标题】:Randomly remove and save elements from matrix从矩阵中随机删除和保存元素
【发布时间】:2018-01-30 12:17:31
【问题描述】:

我用 Python 写了这段代码 sn-p:

def remove_randomly(data, percentage):
    test_list = []
    np.random.shuffle(data)
    for i in range(data.shape[0]):
        for j in range(data.shape[1]):
            roll = np.random.randint(low=1, high=100)
            if roll > percentage:
                test_list.append((i, j, data[i, j]))
                data[i, j] = 0

它获取矩阵数据和一个数字百分比,遍历整个矩阵,并将元素归零(100 - 百分比)并将它们保存到另一个名为 test_list 的对象中。

有没有更好、更有效的方法来实现这个结果?我听说嵌套循环对您的健康有害。另外,我的数据矩阵恰好很大,所以使用 for 循环进行迭代非常慢。

示例

假设数据是矩阵[1, 2; 3, 4],百分比为 25%。

然后我希望输出是(例如)data = [1, 2; 0, 4] 和 test_list = [(1, 0, 3)]

【问题讨论】:

  • 你能举个例子吗?
  • @VikasDamodar 对不起,我不认为我理解你?
  • 通过运行此代码,您期望得到什么结果?
  • 随机选择数据矩阵中的 (100 - percent)% 的条目并插入到列表中,然后在矩阵本身中变为零。

标签: python numpy matrix


【解决方案1】:

您可以这样做:

def remove_randomly(data, percent):
    np.random.shuffle(data)
    roll = np.random.randint(1, 100, data.shape) # array of random integers with the same shape as data
    indices = np.where(roll > percent) # indices of elements in `roll` that are greater than the percentage 

    test_list = data[indices]
    data[indices] = 0

    return indices, test_list # return indices and the values

注意np.random.randint(1, 100)只会生成[1, 100)范围内的随机整数,所以永远不会生成100%。

【讨论】:

    猜你喜欢
    • 2014-09-21
    • 2012-02-13
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2012-11-24
    相关资源
    最近更新 更多