0
votes

I have a rasterstack with 94 bands. The pixel values in the raster vary from 1-30 and represent spectral categories. The bands represent a date. Now I would like to count for each band the number of pixels in each class.
e.g. band 1 has 200 pix of category 1 and 300 pix of category 23 etc...

In the forum I found some related answers so I manged to count the pixels with the following code:

raster = gdal.Open(data)

# empty dicionary 
mydic = {"klasse":[],"count":[]}

# count pixel per catgory for each band and write it to a dictionary
for band in range(1, bands+1):
    data = raster.GetRasterBand(band).ReadAsArray().astype('float')
    data = data[~np.isnan(data)] # remove nan values
    uni = np.unique(data,return_counts=True)  #count unique values
    mydic["klasse"].append(uni[0])
    mydic["count"].append(uni[1])
    
# make a dataframe from the dictionary
df = pd.DataFrame.from_dict(mydic)

What I get is actually nearly what I need, just the output format should be different. I get this:

enter image description here

But I would like something like that:

enter image description here

Any hints how do to that if possible at all? Thank you!

1

1 Answers

0
votes

One way is to try with explode:

df = pd.DataFrame(mydic)
(pd.DataFrame({c:df[c].explode() for c in mydic})
   .set_index('klasse', append=True)['count']
   .unstack(fill_value=0)
)

Output:

klasse   1    3   4   6    7  8    25  27
0        77  358   0   0  138  4    0   0
1         0    0   0   0    0  0  577   0
2       365  114  23  35    5  0    0  35