I have a 10x20 numpy array
[[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255]]
I want to get the repetition of number 0(island of 0's) in the form of a array of dimensions . Like in the example above if I pass the number 0
as parameter the function should go from top to down through the matrix and then go from left to right resulting in the dimensional array. The output for above example should be
#Zeroes repetition dimensions
[[20,4],[3,5],[2,5]]
How can I get this output. Any numpy functions to do this? Thanks in advance.
I would use itertools groupby
for this:
import numpy as np
from itertools import groupby
from collections import Counter
arr=np.array([[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255],
[255,255,255,255,255,255,255,0,0,0,255,255,0,0,255,255,255,255,255,255]])
val_to_check=0
agg_res=[]
for a in arr:
groups = groupby(a)
temp = [[label, sum(1 for _ in group)] for label, group in groups]
for t in temp:
if t[0]==val_to_check:
agg_res.append(t)
res_to_group=[l[1] for l in agg_res]
final_res=Counter(res_to_group)
#or, in list form:
res_list=map(list,final_res.items())
output:
[[2, 5], [3, 5], [20, 4]]
Or, if you want, as a function:
def find_islands(arr,val):
agg_res=[]
for a in arr:
groups = groupby(a)
temp = [[label, sum(1 for _ in group)] for label, group in groups]
for t in temp:
if t[0]==val:
agg_res.append(t)
res_to_group=[l[1] for l in agg_res]
final_res=Counter(res_to_group)
#or, in list form:
return map(list,final_res.items())
example run:
In[65]: find_islands(arr,255)
Out[65]: [[2, 5], [20, 1], [6, 5], [7, 5]]