rioxarray | geospatial xarray extension powered by rasterio | Dataset library
kandi X-RAY | rioxarray Summary
kandi X-RAY | rioxarray Summary
geospatial xarray extension powered by rasterio
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
- Compute raster
- Return the numpy dtype for the given dtype
- Ensures that the nodata s dtype is correct
- Get numpy dtype dtype dtype and numpy dtype dtype dtype
- Get an item from a window
- Return a file handle
- Read data from a window
- Return indexer for rasterio dataset
- Coordinate of the rasterio object
- Set the crs attribute
- Create a raster from a user input
- The grid mapping
- Check if object has spatial dimensions
- Return the number of items in this array
- Check the dimensions of the data arrays
- X dimension
- The y dimension
rioxarray Key Features
rioxarray Examples and Code Snippets
In [7]: countries = gpd.read_file('https://naturalearth.s3.amazonaws.com/110m_cultural/ne_110m_admin_0_countries.zip')
In [13]: sample = np.arange(100)
...: ddm = np.arange(4)
...: timestep = pd.date_range(
import geopandas as gpd
import xarray as xr
import rioxarray
from shapely.geometry import mapping
# load shapefile with geopandas
radar_north = gpd.read_file('radar_north140.shp')
# load ERA5 netcdf with xarray
era = xr.open_dataset('ERA
ds = xr.Dataset({'u': ucomp, 'v': 'vcomp'})
ds.plot.streamplot(x="x", y="y", u="u", v="v")
plt.streamplot(
ux.ravel(),
uy.ravel(),
ucomp.values.ravel(),
vcomp.values.ravel(),
)
class Printable:
def __init__(self, obj):
self._obj = obj
def print_me(self):
print(
type(self).__name__.lower()
+ '\n'
+ str(self._obj)
)
class A(Printable):
pass
class
import rioxarray as rxr
modis = rxr.open_rasterio('/Users/sayantanmandal/Projects/MODIS/MOD09GQ.
A2010200.h26v06.061.2021166023144.hdf', masked = True)
type(modis)
xarray.core.dataset.Dataset
xr.concat(
[
raster_1,
raster_2.reset_coords('band', drop=True).expand_dims(band=[232]),
], dim='band',
)
xds.x.values
array([-113. , -112.99972222, -112.99944444, ..., -112.00083333,
-112.00055556, -112.00027778])
(xds.x.values + 113)*3600
array([0.000e+00, 1.000e+00, 2.000e+00, ..., 3.597e+03, 3.598e+03,
3.599e+03])
import rioxarray
crs = "+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"
stacked = stacked.rio.set_spatial_dims(x_dim="x", y_dim="y").rio.write_grid_mapping().rio.write_crs(crs).rio.write_coordinate_system()
file_to_reproject = xr.open_dataarray("myfile.nc",decode_coords="all")
tiff_rio_500 = rioxarray.open_rasterio('/content/mw/mw_dist_to_light_at_all_from_light_mask_mw_cut_s3_500.tif').rio.reproject('EPSG:3857')
hv_dataset_500_meters = hv.Dataset(tiff_rio_500[0], name='nightlights', vdims='cumulative_cost')
hv_
Community Discussions
Trending Discussions on rioxarray
QUESTION
A have a netCDF file that I opened with xarray. I want to clip the xarray data set using a shapefile; however, I cannot figure out how to properly set my spatial dimensions.
I have the following data set:
print(ds.keys())
ANSWER
Answered 2022-Apr-15 at 17:02rioxarray expects your data to be on a regular grid. Your data appears to be observational data, with a lat, lon value given for the position (of a given spacecraft maybe?) at that time step. You will not be able to expand the dimensions of your array to include (lat, lon).
Instead, you can build an array indicating whether a given (sample, ddm)
point is contained in a shapefile using the arrays sp_lat
, sp_lon
directly.
For example, if you have a shapefile of countries:
QUESTION
I am attempting to generate a streamplot in Matplotlib using u-component & v-component winds from a gridded analysis, and am unsure how to compile these arrays into the Streamplot function. These data are two-dimensional, in GeoTIFF format, and is read into Python using xarray/rioxarray as follows:
...ANSWER
Answered 2022-Mar-13 at 19:37The simplest way to do this is definitely to use xarray.Dataset.plot.streamplot
:
QUESTION
I want to export a single date and variable fwi
of a xarray dataset ds
to a tif file. However, my dataarray has too many dimensions and I cannot figure out how to effectively remove the dimension lsm_time
.
ANSWER
Answered 2022-Feb-14 at 18:35Dimensions with size 1 can be removed using the .squeeze
method.
Conversely, you can add a dimension of size 1 using .expand_dims
QUESTION
I have a script that used to work for calculating zonal statistics (median), but now I get the AttributeError: 'DatasetReader' object has no attribute 'affine'. Here is my code:
...ANSWER
Answered 2022-Jan-13 at 21:13affine
has been deprecated. transform
now accepts GDAL and Affine style transforms.
From Migrating to Rasterio 1.0 affine.Affine() vs. GDAL-style geotransforms:
https://rasterio.readthedocs.io/en/latest/topics/migrating-to-v1.html
Since the above changes, several functions have been added to Rasterio that accept a transform argument. Rather than add an affine argument to each, the transform argument could be either an Affine() object or a GDAL geotransform, the latter issuing the same deprecation warning.
The original plan was to remove the affine argument + property, and assume that the object passed to transform is an Affine(). However, after further discussion it was determined that since Affine() and GDAL geotransforms are both 6 element tuples users may experience unexplained errors and outputs, so an exception is raised instead to better highlight the error.
QUESTION
This question is related, but somehow I still need some help to get this to work. xarray select nearest lat/lon with multi-dimension coordinates
...ANSWER
Answered 2021-Dec-28 at 17:45Actually the longitude and latitude are evenly space at 1/3600 degrees. We can see that with:
QUESTION
So I want to merge 2 datasets, 1 is a single band raster dataset that came from rioxarray.open_rasterio(), the other a lookup table, with an index dim 'mukey'. The coords along 'mukey' correspond to 'mukey' index values in the lookup table. The desired result is a dataset with identical x and y coords to the Raster dataset, with variables 'n' and 'K' whose values are populated by merging on the 'mukey'. If you are familiar with ArcGIS, this is the analogous operation.
xr.merge() and assign() don't quite seem to perform this operation, and cheating by converting into pandas or numpy hits memory issues on my 32GB machine. Does xarray provide any support for this simple use case? Thanks,
...ANSWER
Answered 2021-Dec-14 at 02:22You're looking for the advanced indexing with DataArrays feature of xarray.
You can provide a DataArray
as a keyword argument to DataArray.sel
or Dataset.sel
- this will reshape the indexed array along the dimensions of the indexing array, based on the values of the indexing array. I think this is exactly what you're looking for in a "lookup table".
In your case:
QUESTION
I have a raster file and a shapefile containing polygons. For each polygon, I want to compute the mean value of all raster cells within that polygon.
I had been doing this with rasterstats.zonal_stats
, which works perfectly but is very slow for large rasters.
Recently I came across rioxarray's example of instead clipping the raster to the polygon and then computing the mean.
From my experiments, the clipping approach is a lot faster than zonal_stats and the results are the same.
I am therefore wondering if there is anything else except for the time difference that would lead to a preference of one over the other method?
And why it is that the clipping is so much faster than the zonal_stats
?
Below the output and timing of the two methods, and a snippet of the code. The full code can be found here.
It would be great to get insights on this :)
...ANSWER
Answered 2021-Aug-17 at 14:56In the view of self-learning, I realized I made a mistake here and I think it is beneficial to report.
It all depends on the order you run the functions in. As I loaded the raster data with rioxarray.open_rasterio
, this data is not loaded into memory. Thereafter both the clip and zonal_stats
still have to load this into memory. When one of the two is called before the other, the latter makes use of the fact that the data is already loaded.
You can also choose to instead call ds.load()
before calling the fuctions. In my tests this didn't change the total computation time.
QUESTION
I have a "dataarray" which I am trying to reproject it using rioxarray. However after reprojection when I use xarray.to_netcdf, the saved file is a dataset where the "spatial_ref" coordinate converted to a variable. I am not sure if that is xarray or rioxarray.reprojection causes this behavior. Here are some codes that show the issue:
...ANSWER
Answered 2021-Apr-29 at 17:43The issue was I did not set decode_coords="all" when I used xarray.open_dataarray. With the following everything looks ok:
QUESTION
I am trying to follow simple example in rioxarray documentation to export a dataset to a raster file in DBFS.
Install the library:
...ANSWER
Answered 2021-May-31 at 12:25I suspect that this is caused by the limitations of the DBFS local file API, although the library doesn't throw the exception - just simply don't create a file.
The solution would be to output raster to the local disk, and copy file into the DBFS using dbutils.fs.cp
:
QUESTION
I have a Geotiff that I display on a tile map, but it's slightly off to the south. For example, on this screenshot the edge of the image should be where the country border is, but it's a bit to the south:
Here's the relevant part of the code:
...ANSWER
Answered 2021-Apr-16 at 00:32I've got the answer on the Holoviz Discourse from one of the developers. Seeing how the recommended function is practically undocumented, I copy it here in case somebody looks for an easy way to load a geotiff and add to a tilemap in Holoviews/Geoviews:
philippjfr
I wouldn’t expect manually transforming the coordinates to work particularly well. While it’s a much heavier weight dependency for accurate coordinate transforms I’d recommend using GeoViews.img = gv.util.load_tiff( '/content/mw/mw_dist_to_light_at_all_from_light_mask_mw_cut_s3_500.tif' ) gv.tile_sources.OSM() * img.opts(cmap='inferno_r')
Edit: Now it is possible one doesn't want to use Geoviews as it has a pretty heavy dependency chain that requires a lot of patience and luck to set it up right. Fortunately rioxarray (through rasterio) has a tool to reproject, just append ".rio.reproject('EPSG:3857')" to the first line and then you don't have to use the lnglat_to_meters which is not intended for this purpose.
So the corrected code becomes:
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install rioxarray
You can use rioxarray like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page