【问题标题】:joining two numpy arrays by the elements of the first array [duplicate]通过第一个数组的元素连接两个numpy数组[重复]
【发布时间】:2021-07-23 23:43:50
【问题描述】:
a = np.array([[383, 383, 384, 384, 384, 384, 384, 384, 384, 421, 422, 422, 422, 422, 423, 423, 423, 423, 423, 423, 479, 480, 481, 482, 483, 485, 485, 485, 485, 485, 485, 485, 513, 515, 517]])
b = np.array([384, 423, 485])
np.where(a == b[:,None])

返回两个数组

[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
[2, 3, 4, 5, 6, 7, 8, 14, 15, 16, 17, 18, 19, 25, 26, 27, 28, 29, 30, 31]

我想加入?(我不知道如何调用该操作)通过第一个的值列出两个列表,所以输出会像

[[2, 3, 4, 5, 6, 7, 8], [14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31]]

我该怎么做?

(我的最终任务是获取最后一个数组中每个列表的中心值)

【问题讨论】:

  • 请把ab的内容贴出来
  • 我认为这可能被称为“分组”操作而不是加入操作。
  • @not_speshal 我添加了值
  • 如果副本不清楚c, d = np.where(a == b[:, None]) 然后np.split(d, np.unique(c, return_index=True)[1][1:])

标签: python numpy


【解决方案1】:

你可以这样做:

>>> [np.where(a==x)[1] for x in b]
[array([2, 3, 4, 5, 6, 7, 8], dtype=int64),
 array([14, 15, 16, 17, 18, 19], dtype=int64),
 array([25, 26, 27, 28, 29, 30, 31], dtype=int64)]

如果您希望输出为列表而不是数组:

>>> [list(np.where(a==x)[1]) for x in b]
[[2, 3, 4, 5, 6, 7, 8], [14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多