我正在寻找以下问题的解决方案:
假设我有一个形状为(4,4)的数组:
[5. 4. 5. 4.]
[2. 3. 5. 5.]
[2. 1. 5. 1.]
[1. 3. 1. 3.]
在此数组中,有一列,其中值“ 5”连续出现3次。也就是说,它们不会分散在整个列中,如下所示。
[5.] # This
[1.] # Should
[5.] # Not
[5.] # Count
现在让我们说我有一个形状(M,N)的较大数组,且各种整数值在1-5的相同范围内。如何计算每列中一行出现的相同值的最大数量?此外,是否可以获得这些值出现的索引?上面示例的预期输出为
Found 3 in a row of number 5 in column 2
(0,2), (1,2), (2,2)
我假设如果搜索应关注行,则实现方式将相似。如果不是,我也想知道这是如何完成的。
答案 0 :(得分:1)
方法1
这是一种方法-
def find_longest_island_indices(a, values):
b = np.pad(a, ((1,1),(0,0)), 'constant')
shp = np.array(b.shape)[::-1] - [0,1]
maxlens = []
final_out = []
for v in values:
m = b==v
idx = np.flatnonzero((m[:-1] != m[1:]).T)
s0,s1 = idx[::2], idx[1::2]
l = s1-s0
maxidx = l.argmax()
longest_island_flatidx = np.r_[s0[maxidx]:s1[maxidx]]
r,c = np.unravel_index(longest_island_flatidx, shp)
final_out.append(np.c_[c,r])
maxlens.append(l[maxidx])
return maxlens, final_out
样品运行-
In [169]: a
Out[169]:
array([[5, 4, 5, 4],
[2, 3, 5, 5],
[2, 1, 5, 1],
[1, 3, 1, 3]])
In [173]: maxlens
Out[173]: [1, 2, 1, 1, 3]
In [174]: out
Out[174]:
[array([[3, 0]]), array([[1, 0],
[2, 0]]), array([[1, 1]]), array([[0, 1]]), array([[0, 2],
[1, 2],
[2, 2]])]
# With "pretty" printing
In [171]: maxlens, out = find_longest_island_indices(a, [1,2,3,4,5])
...: for l,o,i in zip(maxlens,out,[1,2,3,4,5]):
...: print "For "+str(i)+" : L= "+str(l)+", Idx = "+str(o.tolist())
For 1 : L= 1, Idx = [[3, 0]]
For 2 : L= 2, Idx = [[1, 0], [2, 0]]
For 3 : L= 1, Idx = [[1, 1]]
For 4 : L= 1, Idx = [[0, 1]]
For 5 : L= 3, Idx = [[0, 2], [1, 2], [2, 2]]
方法2
进行一些修改并输出最大长度岛的开始和结束索引,这是一个-
def find_longest_island_indices_v2(a, values):
b = np.pad(a.T, ((0,0),(1,1)), 'constant')
shp = b.shape
out = []
for v in values:
m = b==v
idx = np.flatnonzero(m.flat[:-1] != m.flat[1:])
s0,s1 = idx[::2], idx[1::2]
l = s1-s0
maxidx = l.argmax()
start_index = np.unravel_index(s0[maxidx], shp)[::-1]
end_index = np.unravel_index(s1[maxidx]-1, shp)[::-1]
maxlen = l[maxidx]
out.append([v,maxlen, start_index, end_index])
return out
样品运行-
In [251]: a
Out[251]:
array([[5, 4, 5, 4],
[2, 3, 5, 5],
[2, 1, 5, 1],
[1, 3, 1, 3]])
In [252]: out = find_longest_island_indices_v2(a, [1,2,3,4,5])
In [255]: out
Out[255]:
[[1, 1, (3, 0), (3, 0)],
[2, 2, (1, 0), (2, 0)],
[3, 1, (1, 1), (1, 1)],
[4, 1, (0, 1), (0, 1)],
[5, 3, (0, 2), (2, 2)]]
# With some pandas styled printing
In [253]: import pandas as pd
In [254]: pd.DataFrame(out, columns=['Val','MaxLen','StartIdx','EndIdx'])
Out[254]:
Val MaxLen StartIdx EndIdx
0 1 1 (3, 0) (3, 0)
1 2 2 (1, 0) (2, 0)
2 3 1 (1, 1) (1, 1)
3 4 1 (0, 1) (0, 1)
4 5 3 (0, 2) (2, 2)
答案 1 :(得分:0)
如果我们将一列相同值的最大长度存储在变量的一列中,那么我们可以迭代查找更大长度的列。
如果以下内容需要更多说明,请说!!
a = np.array([[5,4,5,4],[2,3,5,5],[2,1,5,1],[1,3,1,3]])
rows, cols = a.shape
max_length = 0
for ci in range(cols):
for ri in range(rows):
if ri == 0: #start of run
start_pos = (ri, ci)
length = 1
elif a[ri,ci] == a[ri-1,ci]: #during run
length += 1
else: #end of run
if length > max_length:
max_length = length
max_pos = start_pos
max_row, max_col = max_pos
print('Found {} in a row of number {} in column {}'.format(max_length, a[max_pos], max_col))
for i in range(max_length):
print((max_row+i, max_col))
输出:
Found 3 in a row of number 5 in column 2
(0, 2)
(1, 2)
(2, 2)
请注意,如果您希望元组的输出具有您声明的确切格式,则可以将{-{1}}的generator-expression使用:
str.join
答案 2 :(得分:0)
另一种方法是使用@user建议的itertools.groupby,可能的实现如下:
import numpy as np
from itertools import groupby
def runs(column):
max_run_length, start, indices, max_value = -1, 0, 0, 0
for val, run in groupby(column):
run_length = sum(1 for _ in run)
if run_length > max_run_length:
max_run_length, start, max_value = run_length, indices, val
indices += run_length
return max_value, max_run_length, start
上面的函数为给定的列(行)计算最大行程的长度,起点和相应的值。使用这些值,您可以计算预期的输出。对于阵列[5., 5., 5., 1.]
,groupby是完成所有繁重任务的一个,
[(val, sum(1 for _ in run)) for val, run in groupby([5., 5., 5., 1.])]
上一行输出:[(5.0, 3), (1.0, 1)]
。循环保留最大行程的起始索引,长度和值。要将功能应用于列,您可以使用
numpy.apply_along_axis:
data = np.array([[5., 4., 5., 4.],
[2., 3., 5., 5.],
[2., 1., 5., 1.],
[1., 3., 1., 3.]])
result = [tuple(row) for row in np.apply_along_axis(runs, 0, data).T]
print(result)
输出
[(2.0, 2.0, 1.0), (4.0, 1.0, 0.0), (5.0, 3.0, 0.0), (4.0, 1.0, 0.0)]
在第四元组上方的输出对应于第四列,最长连续运行的值为5
,长度为3
,并从索引0
开始。要更改为行而不是列,请将轴的索引更改为1
并删除T,如下所示:
result = [tuple(row) for row in np.apply_along_axis(runs, 1, data)]
输出
[(5.0, 1.0, 0.0), (5.0, 2.0, 2.0), (2.0, 1.0, 0.0), (1.0, 1.0, 0.0)]