MAS*_*MAS 6 python numpy scipy
我想在我的数组中找到1的最长序列的起始位置:
a1=[0,0,1,1,1,1,0,0,1,1]
#2
Run Code Online (Sandbox Code Playgroud)
我按照这个答案找到最长序列的长度.但是,我无法确定位置.
Div*_*kar 10
受 启发this solution,这是一种解决它的矢量化方法 -
# Get start, stop index pairs for islands/seq. of 1s
idx_pairs = np.where(np.diff(np.hstack(([False],a1==1,[False]))))[0].reshape(-1,2)
# Get the island lengths, whose argmax would give us the ID of longest island.
# Start index of that island would be the desired output
start_longest_seq = idx_pairs[np.diff(idx_pairs,axis=1).argmax(),0]
Run Code Online (Sandbox Code Playgroud)
样品运行 -
In [89]: a1 # Input array
Out[89]: array([0, 0, 1, 1, 1, 1, 0, 0, 1, 1])
In [90]: idx_pairs # Start, stop+1 index pairs
Out[90]:
array([[ 2, 6],
[ 8, 10]])
In [91]: np.diff(idx_pairs,axis=1) # Island lengths
Out[91]:
array([[4],
[2]])
In [92]: np.diff(idx_pairs,axis=1).argmax() # Longest island ID
Out[92]: 0
In [93]: idx_pairs[np.diff(idx_pairs,axis=1).argmax(),0] # Longest island start
Out[93]: 2
Run Code Online (Sandbox Code Playgroud)