我必须从numpy数组中聚集连续元素.考虑以下示例
a = [ 0, 47, 48, 49, 50, 97, 98, 99]
Run Code Online (Sandbox Code Playgroud)
输出应该是一个元组列表,如下所示
[(0),(47, 48, 49, 50),(97, 98, 99)]
Run Code Online (Sandbox Code Playgroud)
这里差别只是一个.元素之间.如果差异也可以指定为限制或硬编码数字,那将是很好的.
非常感谢.
unu*_*tbu 157
def consecutive(data, stepsize=1):
return np.split(data, np.where(np.diff(data) != stepsize)[0]+1)
a = np.array([0, 47, 48, 49, 50, 97, 98, 99])
consecutive(a)
Run Code Online (Sandbox Code Playgroud)
产量
[array([0]), array([47, 48, 49, 50]), array([97, 98, 99])]
Run Code Online (Sandbox Code Playgroud)
dka*_*ins 19
这是一个可能有帮助的lil功能:
def group_consecutives(vals, step=1):
"""Return list of consecutive lists of numbers from vals (number list)."""
run = []
result = [run]
expect = None
for v in vals:
if (v == expect) or (expect is None):
run.append(v)
else:
run = [v]
result.append(run)
expect = v + step
return result
>>> group_consecutives(a)
[[0], [47, 48, 49, 50], [97, 98, 99]]
>>> group_consecutives(a, step=47)
[[0, 47], [48], [49], [50, 97], [98], [99]]
Run Code Online (Sandbox Code Playgroud)
Pau*_*aul 10
(a[1:]-a[:-1])==1 将产生一个布尔数组,False表示运行中断.您也可以使用内置的numpy.grad.
测试一维数组
获取diff不为一的地方
diffs = numpy.diff(array) != 1
Run Code Online (Sandbox Code Playgroud)
获取 diff 的索引,获取第一个维度并对所有维度加一,因为diff与前一个索引进行比较
indexes = numpy.nonzero(diffs)[0] + 1
Run Code Online (Sandbox Code Playgroud)
使用给定索引进行拆分
groups = numpy.split(array, indexes)
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所提出的:不确定是100%正确
import numpy as np
a = np.array([ 0, 47, 48, 49, 50, 97, 98, 99])
print np.split(a, np.cumsum( np.where(a[1:] - a[:-1] > 1) )+1)
Run Code Online (Sandbox Code Playgroud)
收益:
>>>[array([0]), array([47, 48, 49, 50]), array([97, 98, 99])]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31164 次 |
| 最近记录: |