从矩阵中随机删除并保存元素

2024-03-28 16:11:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python编写了以下代码片段:

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]和测试列表=[(1,0,3)]


Tags: 数据代码intestfordatanprange
3条回答

以下是您可以做的:

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%

相关问题 更多 >