Numpy: Function to take arrays a and b and return array c with elements 0:b[0] with value a[0], values b[0]:b[1] with value a[1], and so on

huangapple go评论58阅读模式
英文:

Numpy: Function to take arrays a and b and return array c with elements 0:b[0] with value a[0], values b[0]:b[1] with value a[1], and so on

问题

有没有一种快速的内置numpy函数可以实现这个目标?

英文:

Say I have two arrays:

a = np.asarray([0,1,2])
b = np.asarray([3,7,10])

Is there a fast way to create:

c = np.asarray([0,0,0,1,1,1,1,2,2,2])
#  index             3       7     10

This can be done using a for loop but I wonder if there is a fast internal numpy function that achieves the same thing.

答案1

得分: 2

你可以使用diff来获得连续的差异,r_来添加第一个b值,以及repeat来重复数值:

a = np.asarray([0, 1, 2])
b = np.asarray([3, 7, 10])

c = np.repeat(a, np.r_[b[0], np.diff(b)])

输出:array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2])

英文:

You can use diff to get the successive differences, r_ to add the first b value and repeat to duplicate the values:

a = np.asarray([0, 1, 2])
b = np.asarray([3, 7, 10])

c = np.repeat(a, np.r_[b[0], np.diff(b)])

Output: array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2])

huangapple
  • 本文由 发表于 2023年2月9日 01:05:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定