【发布时间】:2022-01-01 16:09:04
【问题描述】:
假设我有以下升序整数数组(有些可能是负数):
a = np.array([ 1, 1, 1, 1, 10, 10, 20, 20, 20, 30, 40, 40, 40, 40])
我想把它变成这样:
a = np.array([ 1, 2, 3, 4, 10, 11, 20, 21, 22, 30, 40, 41, 42, 43])
...其中每组相同整数中的每个整数都会递增,因此对于第一个 1:
1 1 1 1 <--- these are the numbers from the array
+ 0 1 2 3 <--- these are counts of the number for its group
-------
1 2 3 4
有没有比以下更有效的方法?
a = np.array([ 1, 1, 1, 1, 10, 10, 20, 20, 20, 30, 40, 40, 40, 40])
ones = (a == np.pad(a, (1,0))[:-1]).astype(int)
ones[ones == 0] = -np.diff(np.concatenate(([0.], np.cumsum(ones != 0)[ones == 0])))
new_a = a + ones.cumsum()
注意数组总是按升序排列(从小到大),数字总是整数,有些可能是负数。
解释,如果你不明白:
在this post 的帮助下,我实际上已经完成了这项工作。我现在正在做的是生成一个这样的数组,其中 0 表示一组相同数字中的第一个,1 表示其余的:
1 1 1 1 10 10 20 20 20 30 40 40 40 40
0 1 1 1 0 1 0 1 1 0 0 1 1 1
^ first 1 ^ first 10 ^ first 30
^ first 20 ^ first 40
然后使用上面链接的帖子中的技术来计算该数组中的所有内容:
# Shift `a` by one and compare it with the original array
>>> ones = (a == np.pad(a, (1,0))[:-1]).astype(int)
>>> ones
array([0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1])
# This line is from the linked post (modified, of course)
>>> ones[ones == 0] = -np.diff(np.concatenate(([0.], np.cumsum(ones != 0)[ones == 0])))
>>> ones
array([ 0, 1, 1, 1, -3, 1, -1, 1, 1, -2, 0, 1, 1, 1])
>>> ones.cumsum()
array([0, 1, 2, 3, 0, 1, 0, 1, 2, 0, 0, 1, 2, 3])
现在,我们可以将结果数组添加到原始数组中:
>>> a
array([ 1, 1, 1, 1, 10, 10, 20, 20, 20, 30, 40, 40, 40, 40])
>>> a + ones.cumsum()
array([ 1, 2, 3, 4, 10, 11, 20, 21, 22, 30, 40, 41, 42, 43])
【问题讨论】: