Python – How to Get All Unique Raster Values of Intersecting Vector in Python

land-coverpythonrasterstatszonal statistics

I have a tif-file containing categorical numerical land cover values and a gdf-file containing roads as linestrings. I'd like to create a new column to the road gdf that contains all unique intersecting land-cover classes (and perhaps even their share of intersection in %).

So far, I thought about using rasterstats cause I would like to avoid using gdal. However, if I use the zonal_stats function I don't see a way to show all unique values

import rasterstats
df['lc_major'] = zonal_stats(df, 
                             landcover_tif, 
                             stats="majority")

In fact, I can only choose between:

['count', 'min', 'max', 'mean', 'sum', 'std', 'median', 'majority',
'minority', 'unique', 'range', 'nodata', 'nan']

'unique' only gives the amount of unique values, but not their values itself. So, I could work with minority, majority, min and/or max if unique is <= 2, but I doubt that's the smartest way to get there. Any ideas how to approach this somehow smarter?

Best Answer

Found an answer. Had to add "categorical=True", to get the amount of counts per category.

import rasterstats
df['lc_major'] = zonal_stats(df, 
                             landcover_tif, 
                             stats="majority", # any other stat will also do
                             categorical=True)