【问题标题】:Select two rows from bit array based on int array python基于int数组python从位数组中选择两行
【发布时间】:2017-02-27 21:44:59
【问题描述】:

我有两个数组,一个是 Int,一个是 bit

s = [ [1]          x = [ [1 0 0 0 0]
      [4]              [1 1 1 1 0]
      [9]              [0 1 1 1 0]
      [0]              [0 0 1 0 0]
      [3] ]            [0 1 1 0 0]]

我想找到 s 中最小的两个元素(随机给定),然后(选择并打印)基于 s 数组的 x(随机给定)中的两行, 比如s[i]中最小的元素是s[3]=0,s[0]=1,所以我要选择x[3][0 0 1 0 0],x[0][1 0 0 0 0]

import numpy as np
np.set_printoptions(threshold=np.nan)
s= np.random.randint(5, size=(5))
x= np.random.randint (2, size=(5, 5))
print (s)
print (x)

我已尽力使用“for 循环”,但没有运气,任何建议都将不胜感激。

【问题讨论】:

  • 请分享您在 for 循环上的努力,以便我们帮助您修复或更正它。
  • 我也喜欢,不过不是很清楚,不然分享一下,谢谢

标签: python python-3.x numpy for-loop


【解决方案1】:

您可以使用numpy.argpartition 找出s 中两个最小元素的索引,并将其用作子集x 的行索引:

s
# array([3, 0, 0, 1, 2])

x
# array([[1, 0, 0, 0, 1],
#        [1, 0, 1, 1, 1],
#        [0, 0, 1, 0, 0],
#        [1, 0, 0, 1, 1],
#        [0, 0, 1, 0, 1]])

x[s.argpartition(2)[:2], :]
# array([[1, 0, 1, 1, 1],
#        [0, 0, 1, 0, 0]])

【讨论】:

  • 非常感谢您的帮助
猜你喜欢
  • 2019-01-11
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
  • 2014-05-15
  • 2021-12-14
  • 2017-11-19
相关资源
最近更新 更多