简体   繁体   English

光栅 - 计算光栅堆栈中每个类别的像素并写入 dataframe 和 python

[英]Raster - count pixel per category in rasterstack and write in dataframe with python

I have a rasterstack with 94 bands.我有一个包含 94 个波段的栅格堆栈。 The pixel values in the raster vary from 1-30 and represent spectral categories.栅格中的像素值从 1 到 30 不等,代表光谱类别。 The bands represent a date.这些带代表一个日期。 Now I would like to count for each band the number of pixels in each class.现在我想为每个波段计算每个 class 中的像素数。
eg band 1 has 200 pix of category 1 and 300 pix of category 23 etc...例如,带 1 有 200 类 1 像素和 300 类 23 像素等......

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.我得到的实际上几乎是我需要的,只是 output 格式应该不同。 I get this:我明白了:

在此处输入图像描述

But I would like something like that:但我想要这样的东西:

在此处输入图像描述

Any hints how do to that if possible at all?如果可能的话,任何提示如何做到这一点? Thank you!谢谢!

One way is to try with explode :一种方法是尝试使用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: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM