Python 从索引位置列表中创建非均匀(随机)间隔的排列?
假设我有一个1上的数组和一个位置列表:Python 从索引位置列表中创建非均匀(随机)间隔的排列?,python,numpy,Python,Numpy,假设我有一个1上的数组和一个位置列表: arr = np.ones(35) [3, 5, 8, 12, 14, 17, 19, 25, 27, 33] 在这些不同的点上,我想增加1,这样我就有了一个最终的数组 array([1,1,1,2,2,3,3,3,4,4,4,4,5,5,6,6,6,7,7,8,8,....]) 您可以将repeat与ediff1d一起使用 arr = np.array([3, 5, 8, 12, 14, 17, 19, 25, 27, 33]) res = np.r
arr = np.ones(35)
[3, 5, 8, 12, 14, 17, 19, 25, 27, 33]
在这些不同的点上,我想增加1,这样我就有了一个最终的数组
array([1,1,1,2,2,3,3,3,4,4,4,4,5,5,6,6,6,7,7,8,8,....])
您可以将
repeat
与ediff1d
一起使用
arr = np.array([3, 5, 8, 12, 14, 17, 19, 25, 27, 33])
res = np.repeat(
np.arange(1, arr.shape[0] + 1),
np.ediff1d(arr, to_begin=arr[0])
)
# array([ 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6,
# 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 10, 10, 10])
这可以灵活地选择要重复的第一个参数:
In [81]: np.repeat(
...: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29],
...: np.ediff1d(arr, to_begin=arr[0])
...: )
Out[81]:
array([ 2, 2, 2, 3, 3, 5, 5, 5, 7, 7, 7, 7, 11, 11, 13, 13, 13,
17, 17, 19, 19, 19, 19, 19, 19, 23, 23, 29, 29, 29, 29, 29, 29])
您可以将
repeat
与ediff1d
一起使用
arr = np.array([3, 5, 8, 12, 14, 17, 19, 25, 27, 33])
res = np.repeat(
np.arange(1, arr.shape[0] + 1),
np.ediff1d(arr, to_begin=arr[0])
)
# array([ 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6,
# 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 10, 10, 10])
这可以灵活地选择要重复的第一个参数:
In [81]: np.repeat(
...: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29],
...: np.ediff1d(arr, to_begin=arr[0])
...: )
Out[81]:
array([ 2, 2, 2, 3, 3, 5, 5, 5, 7, 7, 7, 7, 11, 11, 13, 13, 13,
17, 17, 19, 19, 19, 19, 19, 19, 23, 23, 29, 29, 29, 29, 29, 29])
你可以这样做:
arr = np.ones(35)
idx = [3, 5, 8, 12, 14, 17, 19, 25, 27, 33]
for val in idx:
arr[val:] = arr[val:] + 1
(对于那些与Python索引不相似的,符号[val://code>只是从val
索引到数组的末尾。)
然后输出为:
array([ 1., 1., 1., 2., 2., 3., 3., 3., 4., 4., 4., 4., 5.,
5., 6., 6., 6., 7., 7., 8., 8., 8., 8., 8., 8., 9.,
9., 10., 10., 10., 10., 10., 10., 11., 11.])
你可以这样做:
arr = np.ones(35)
idx = [3, 5, 8, 12, 14, 17, 19, 25, 27, 33]
for val in idx:
arr[val:] = arr[val:] + 1
(对于那些与Python索引不相似的,符号[val://code>只是从val
索引到数组的末尾。)
然后输出为:
array([ 1., 1., 1., 2., 2., 3., 3., 3., 4., 4., 4., 4., 5.,
5., 6., 6., 6., 7., 7., 8., 8., 8., 8., 8., 8., 9.,
9., 10., 10., 10., 10., 10., 10., 11., 11.])
另一种解决方案是使用np.searchsorted
:
size = 35
idx = [3, 5, 8, 12, 14, 17, 19, 25, 27, 33]
result = np.searchsorted(idx, np.arange(size), side='right') + 1
另一种解决方案是使用np.searchsorted
:
size = 35
idx = [3, 5, 8, 12, 14, 17, 19, 25, 27, 33]
result = np.searchsorted(idx, np.arange(size), side='right') + 1