numpy中的子列表内的逆序

luaexgnf  于 2023-10-19  发布在  其他
关注(0)|答案(5)|浏览(150)

我有两个numpy数组:

  1. Values = numpy.array([5, 6, 7, 8, 1, 2, 3, 14, 15, 16])
  2. Lengths = numpy.array([4, 3, 3])

在numpy中反转子列表中的顺序来得到这个的有效方法是什么?

  1. [8, 7, 6, 5, 3, 2, 1, 16, 15, 14]

我尝试过for循环,但我相信应该有一种更有效的方法来使用numpy函数。

sz81bmfz

sz81bmfz1#

您可以通过在np.cumsum(Lengths)给定的所需索引处拆分数组(使用np.split),然后在每个索引反转后将它们连接(使用np.concatenate)来实现这一点。

  1. import numpy as np
  2. Values = np.array([5, 6, 7, 8, 1, 2, 3, 14, 15, 16])
  3. Lengths = np.array([4, 3, 3])
  4. res = np.concatenate([split[::-1] for split in np.split(Values, np.cumsum(Lengths))])
  5. print(res)

输出量:

  1. [ 8 7 6 5 3 2 1 16 15 14]
ikfrs5lh

ikfrs5lh2#

对于矢量解决方案,可以使用np.repeat创建一个排序器数组,然后使用np.argsort对数组进行重新排序

  1. a = np.repeat(np.arange(len(Lengths)), Lengths)[::-1]
  2. # array([2, 2, 2, 1, 1, 1, 0, 0, 0, 0])
  3. out = Values[len(Values)-1-np.argsort(a)]

输出量:

  1. array([ 8, 7, 6, 5, 3, 2, 1, 16, 15, 14])

中间体:

  1. len(Values)-1-np.argsort(a)
  2. # array([3, 2, 1, 0, 6, 5, 4, 9, 8, 7])
ukqbszuj

ukqbszuj3#

  1. import numpy as np
  2. Values = np.array([5, 6, 7, 8, 1, 2, 3, 14, 15, 16])
  3. Lengths = np.array([4, 3, 3])
  4. splits = np.split(Values, np.cumsum(Lengths)[:-1]) #splits into 3 parts
  5. reversed_list = [np.flip(split) for split in splits] #flip/reverse all the 3 parts
  6. result = np.concatenate(reversed_list) # join all 3 parts
  7. print(result)
z6psavjg

z6psavjg4#

根据this的讨论,切片是最快的技术之一,你可以用来分割。下面的代码只使用切片,因此不使用任何额外的空间或复制。

  1. import numpy
  2. Values = numpy.array([5, 6, 7, 8, 1, 2, 3, 14, 15, 16])
  3. Lengths = numpy.array([4, 3, 3])
  4. start = 0
  5. end = 0
  6. for i in range(len(Lengths)):
  7. end = end + Lengths[i]
  8. if i == 0: ## Isolate the first scenario as splitting doesn't accept -1 as second argument. [end:-1:step] is not valid
  9. Values[0:end] = Values[end-1::-1]
  10. else:
  11. Values[start:end] = Values[end-1:start-1:-1]
  12. start = end
  13. print(Values)
odopli94

odopli945#

您可以构建一个索引列表,这些索引相对于每个块的最后一个索引反转位置。然后将其用作值数组的间接寻址。

  1. import numpy as np
  2. values = np.array([5, 6, 7, 8, 1, 2, 3, 14, 15, 16])
  3. lengths = np.array([4, 3, 3])
  4. s = np.cumsum(lengths) - 1
  5. s[1:] += s[:-1] + 1
  6. i = np.repeat(s, lengths) - np.arange(values.size)
  7. print(values[i])
  8. # [ 8 7 6 5 3 2 1 16 15 14]

相关问题