【问题标题】:randomly change numpy array values随机更改 numpy 数组值
【发布时间】:2020-07-29 17:20:33
【问题描述】:

我有一个数组数据。

import numpy as np

data = np.array([[1,0,4,1,1,2,0],
                 [1,0,0,4,0,1,0],
                 [4,0,4,3,2,1,0],
                 [4,0,1,1,2,1,1]])

print(data)

如果某些非零元素(1,2,3,4)的计数超过5个,我想随机提取并保留5个位置,并将所有其他位置替换为0。

uniques, counts = np.unique(data, return_counts=True)
for unique, count in zip(uniques, counts):
    print (unique, count)

    if count > 5:       
       
       ids = np.random.choice(range(count), 5, replace=False)

我该怎么做?

【问题讨论】:

  • 当它们的计数超过 5 时,只保留 5 个位置或唯一的非零元素的所有位置?
  • 如果数量超过 5 个,则只保留 5 个位置。

标签: python numpy


【解决方案1】:
uniques, counts = np.unique(data, return_counts=True)
for unique, count in zip(uniques, counts):
    print (unique, count)
    if unique != 0 and count > 5:
       ids = np.random.choice(count, count-5, replace=False)
       data[tuple(i[ids] for i in np.where(data == unique))] = 0

【讨论】:

  • 这条线的替代品是什么,data[tuple(i[ids] for i in np.where(data == unique))] = 0
  • 我听不懂那行
  • 也许这个更容易理解,x,y = np.where(data == unique)for i in ids: data[x[i],y[i]] = 0
猜你喜欢
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-20
  • 2021-10-31
相关资源
最近更新 更多