Compute zonal statistics for a numpy array in rotated-coordinate spaceIs there a NumPy function to return the first index of something in an array?How to print the full NumPy array, without truncation?Find nearest value in numpy arraySorting arrays in NumPy by columnNumpy array dimensionsHow do I read CSV data into a record array in NumPy?How to access the ith column of a NumPy multidimensional array?Dump a NumPy array into a csv fileHow do I get indices of N maximum values in a NumPy array?How to convert 2D float numpy array to 2D int numpy array?

Selecting a secure PIN for building access

Why is the SNP putting so much emphasis on currency plans?

Conflicting terms and the definition of a «child»

What is the word which sounds like "shtrass"?

Accidentally deleted the "/usr/share" folder

Survey Confirmation - Emphasize the question or the answer?

If Melisandre foresaw another character closing blue eyes, why did she follow Stannis?

What are the spoon bit of a spoon and fork bit of a fork called?

Can commander tax be proliferated?

Any examples of headwear for races with animal ears?

Floor tile layout process?

Why do money exchangers give different rates to different bills

Why do freehub and cassette have only one position that matches?

When do aircrafts become solarcrafts?

Can I use 1000v rectifier diodes instead of 600v rectifier diodes?

How long can a 35mm film be used/stored before it starts to lose its quality after expiry?

Password expiration with Password manager

If 1. e4 c6 is considered as a sound defense for black, why is 1. c3 so rare?

Is Cola "probably the best-known" Latin word in the world? If not, which might it be?

Write to EXCEL from SQL DB using VBA script

Public Salesforce Site and Security Review

Airbnb - host wants to reduce rooms, can we get refund?

What is the most remote airport from the center of the city it supposedly serves?

How to get SEEK accessing converted ID via view



Compute zonal statistics for a numpy array in rotated-coordinate space


Is there a NumPy function to return the first index of something in an array?How to print the full NumPy array, without truncation?Find nearest value in numpy arraySorting arrays in NumPy by columnNumpy array dimensionsHow do I read CSV data into a record array in NumPy?How to access the ith column of a NumPy multidimensional array?Dump a NumPy array into a csv fileHow do I get indices of N maximum values in a NumPy array?How to convert 2D float numpy array to 2D int numpy array?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















BLUF::



I'm having trouble computing zonal statistics with a rotated array using the rasterstats package. I'm guessing the problem is with my affine matrix, but I'm not completely sure. Below is the affine transform matrix and output:



| 951.79, 0.45, 2999993.57|
| 0.00,-996.15,-1985797.84|
| 0.00, 0.00, 1.00|


enter image description here



Background:



I am creating files for a groundwater flow model and need to compute zonal statistics for each model grid cell using some .csv data from the Puerto Rico Agricultural Water Management web portal. These data are available on a daily timestep for numerous parameters (e.g. ET, tmax, tmin, precip, etc.). These files are not georeferenced, but ancillary files are available that specify the lon/lat for each cell which can then be projected using pyproj:



import pandas as pd
import numpy as np
import pyproj

url_base = 'http://academic.uprm.edu/hdc/GOES-PRWEB_RESULTS'

# Load some data
f = '/'.join([url_base, 'actual_ET', 'actual_ET20090101.csv'])
array = pd.read_csv(f, header=None).values

# Read longitude values
f = '/'.join([url_base, 'NON_TRANSIENT_PARAMETERS', 'LONGITUDE.csv'])
lon = pd.read_csv(f, header=None).values

# Read latitude values
f = '/'.join([url_base, 'NON_TRANSIENT_PARAMETERS', 'LATITUDE.csv'])
lat = np.flipud(pd.read_csv(f, header=None).values)

# Project to x/y coordinates (North America Albers Equal Area Conic)
aea = pyproj.Proj('+init=ESRI:102008')
x, y = aea(lon, lat)


Before I can compute zonal statistics, I need to create the affine transform that relates row/column coordinates to projected x/y coordinates. I specify the 6 parameters to create the Affine object using the affine library:



import math
from affine import Affine

length_of_degree_longitude_at_lat_mean = 105754.71 # 18.25 degrees via http://www.csgnetwork.com/degreelenllavcalc.html
length_of_degree_latitude_at_lat_mean = 110683.25 # 18.25 degrees via http://www.csgnetwork.com/degreelenllavcalc.html

# Find the upper left x, y
xul, yul = aea(lon[0][0], lat[0][0])
xll, yll = aea(lon[-1][0], lat[-1][0])
xur, yur = aea(lon[0][-1], lat[0][-1])
xlr, ylr = aea(lon[-1][-1], lat[-1][-1])

# Compute pixel width
a = abs(lon[0][1] - lon[0][0]) * length_of_degree_longitude_at_lat_mean

# Row rotation
adj = abs(xlr - xll)
opp = abs(ylr - yll)
b = math.atan(opp/adj)

# x-coordinate of the upper left corner
c = xul - a / 2

# Compute pixel height
e = -abs(lat[1][0] - lat[0][0]) * length_of_degree_latitude_at_lat_mean

# Column rotation
d = 0

# y-coordinate of the upper left corner
f = yul - e / 2

affine = Affine(a, b, c, d, e, f)


where:



  • a = width of a pixel

  • b = row rotation (typically zero)

  • c = x-coordinate of the upper-left corner of the upper-left pixel

  • d = column rotation (typically zero)

  • e = height of a pixel (typically negative)

  • f = y-coordinate of the of the upper-left corner of the upper-left pixel

(from https://www.perrygeo.com/python-affine-transforms.html)



The resulting affine matrix looks reasonable and I've tried passing row and column rotation as both radians and degrees with little change in the result. Link to grid features: grid_2km.geojson



import rasterstats
import matplotlib.pyplot as plt

grid_f = 'grid_2km.geojson'
gdf = gpd.read_file(grid_f)

zs = rasterstats.zonal_stats(gdf,
array,
affine=affine,
stats=['mean'])

df = pd.DataFrame(zs).fillna(value=np.nan)

fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(131, aspect='equal')
ax.pcolormesh(x, y, np.zeros_like(array))
ax.pcolormesh(x, y, array)
ax.set_title('Projected Data')

ax = fig.add_subplot(132, aspect='equal')
gdf.plot(ax=ax)
ax.set_title('Projected Shapefile')

ax = fig.add_subplot(133, aspect='equal')
ax.imshow(df['mean'].values.reshape((gdf.row.max(), gdf.col.max())))
ax.set_title('Zonal Statistics Output')

plt.tight_layout()
plt.show()


enter image description here



Further, there is a discrepancy between x, y value pairs transformed using the affine object versus those derived from the native lon, lat values using pyproj:



rr = np.array([np.ones(x.shape[1], dtype=np.int) * i for i in range(x.shape[0])])
cc = np.array([np.arange(x.shape[1]) for i in range(x.shape[0])])
x1, y1 = affine * (cc, rr)

fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(111, aspect='equal')
ax.scatter(x, y, s=.2)
ax.scatter(x1, y1, s=.2)

plt.show()


enter image description here










share|improve this question
























  • If you have projected data and a projected shapefile, what makes you think its an affine issue? Are you using rasterstats?

    – dubbbdan
    Mar 26 at 13:19











  • @dubbbdan Yes, I'm using the rasterstats package; I've updated the question so that it now shows the zonal statistics computations. x, y values can be returned from the affine by passing row, column pairs and these x, y values do not match those computed directly from the native lon, lat pairs using pyproj which suggests to me that it's a problem with the affine. See the additional figure I added to the post to illustrate.

    – Jason Bellino
    Mar 26 at 17:13











  • rasterstats is a great package! The fact that zonal_stats returns data leads me to believe that everything is fine with you affine. Have you looked at passing the arguement raster_out=True in zonal_stats?

    – dubbbdan
    Mar 26 at 17:26











  • I think the problem is that you are not plotting the zonal statistics properly. Reshaping `df['mean]' isnt enought to assoicate a projected grid with the resulting zonal statistic calculations. Can you provide a link to the shapefile (ideally as geojson)?

    – dubbbdan
    Mar 26 at 17:35












  • @dubbbdan I added a link to the features which are hosted in a GitHub gist (gist.github.com/jbellino-usgs/6be521efec919c1ef5684e1452a069f9). The object returned by zonal_stats is a list of dicts with one dict for each zone feature in the grid shapefile. In this case each dictionary consists of one key and one value since I'm only asking for the mean. If I create a DataFrame from that list of dicts and then reshape the resulting column of data I end up with a numpy array with the same shape as the input grid features.

    – Jason Bellino
    Mar 26 at 18:26

















0















BLUF::



I'm having trouble computing zonal statistics with a rotated array using the rasterstats package. I'm guessing the problem is with my affine matrix, but I'm not completely sure. Below is the affine transform matrix and output:



| 951.79, 0.45, 2999993.57|
| 0.00,-996.15,-1985797.84|
| 0.00, 0.00, 1.00|


enter image description here



Background:



I am creating files for a groundwater flow model and need to compute zonal statistics for each model grid cell using some .csv data from the Puerto Rico Agricultural Water Management web portal. These data are available on a daily timestep for numerous parameters (e.g. ET, tmax, tmin, precip, etc.). These files are not georeferenced, but ancillary files are available that specify the lon/lat for each cell which can then be projected using pyproj:



import pandas as pd
import numpy as np
import pyproj

url_base = 'http://academic.uprm.edu/hdc/GOES-PRWEB_RESULTS'

# Load some data
f = '/'.join([url_base, 'actual_ET', 'actual_ET20090101.csv'])
array = pd.read_csv(f, header=None).values

# Read longitude values
f = '/'.join([url_base, 'NON_TRANSIENT_PARAMETERS', 'LONGITUDE.csv'])
lon = pd.read_csv(f, header=None).values

# Read latitude values
f = '/'.join([url_base, 'NON_TRANSIENT_PARAMETERS', 'LATITUDE.csv'])
lat = np.flipud(pd.read_csv(f, header=None).values)

# Project to x/y coordinates (North America Albers Equal Area Conic)
aea = pyproj.Proj('+init=ESRI:102008')
x, y = aea(lon, lat)


Before I can compute zonal statistics, I need to create the affine transform that relates row/column coordinates to projected x/y coordinates. I specify the 6 parameters to create the Affine object using the affine library:



import math
from affine import Affine

length_of_degree_longitude_at_lat_mean = 105754.71 # 18.25 degrees via http://www.csgnetwork.com/degreelenllavcalc.html
length_of_degree_latitude_at_lat_mean = 110683.25 # 18.25 degrees via http://www.csgnetwork.com/degreelenllavcalc.html

# Find the upper left x, y
xul, yul = aea(lon[0][0], lat[0][0])
xll, yll = aea(lon[-1][0], lat[-1][0])
xur, yur = aea(lon[0][-1], lat[0][-1])
xlr, ylr = aea(lon[-1][-1], lat[-1][-1])

# Compute pixel width
a = abs(lon[0][1] - lon[0][0]) * length_of_degree_longitude_at_lat_mean

# Row rotation
adj = abs(xlr - xll)
opp = abs(ylr - yll)
b = math.atan(opp/adj)

# x-coordinate of the upper left corner
c = xul - a / 2

# Compute pixel height
e = -abs(lat[1][0] - lat[0][0]) * length_of_degree_latitude_at_lat_mean

# Column rotation
d = 0

# y-coordinate of the upper left corner
f = yul - e / 2

affine = Affine(a, b, c, d, e, f)


where:



  • a = width of a pixel

  • b = row rotation (typically zero)

  • c = x-coordinate of the upper-left corner of the upper-left pixel

  • d = column rotation (typically zero)

  • e = height of a pixel (typically negative)

  • f = y-coordinate of the of the upper-left corner of the upper-left pixel

(from https://www.perrygeo.com/python-affine-transforms.html)



The resulting affine matrix looks reasonable and I've tried passing row and column rotation as both radians and degrees with little change in the result. Link to grid features: grid_2km.geojson



import rasterstats
import matplotlib.pyplot as plt

grid_f = 'grid_2km.geojson'
gdf = gpd.read_file(grid_f)

zs = rasterstats.zonal_stats(gdf,
array,
affine=affine,
stats=['mean'])

df = pd.DataFrame(zs).fillna(value=np.nan)

fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(131, aspect='equal')
ax.pcolormesh(x, y, np.zeros_like(array))
ax.pcolormesh(x, y, array)
ax.set_title('Projected Data')

ax = fig.add_subplot(132, aspect='equal')
gdf.plot(ax=ax)
ax.set_title('Projected Shapefile')

ax = fig.add_subplot(133, aspect='equal')
ax.imshow(df['mean'].values.reshape((gdf.row.max(), gdf.col.max())))
ax.set_title('Zonal Statistics Output')

plt.tight_layout()
plt.show()


enter image description here



Further, there is a discrepancy between x, y value pairs transformed using the affine object versus those derived from the native lon, lat values using pyproj:



rr = np.array([np.ones(x.shape[1], dtype=np.int) * i for i in range(x.shape[0])])
cc = np.array([np.arange(x.shape[1]) for i in range(x.shape[0])])
x1, y1 = affine * (cc, rr)

fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(111, aspect='equal')
ax.scatter(x, y, s=.2)
ax.scatter(x1, y1, s=.2)

plt.show()


enter image description here










share|improve this question
























  • If you have projected data and a projected shapefile, what makes you think its an affine issue? Are you using rasterstats?

    – dubbbdan
    Mar 26 at 13:19











  • @dubbbdan Yes, I'm using the rasterstats package; I've updated the question so that it now shows the zonal statistics computations. x, y values can be returned from the affine by passing row, column pairs and these x, y values do not match those computed directly from the native lon, lat pairs using pyproj which suggests to me that it's a problem with the affine. See the additional figure I added to the post to illustrate.

    – Jason Bellino
    Mar 26 at 17:13











  • rasterstats is a great package! The fact that zonal_stats returns data leads me to believe that everything is fine with you affine. Have you looked at passing the arguement raster_out=True in zonal_stats?

    – dubbbdan
    Mar 26 at 17:26











  • I think the problem is that you are not plotting the zonal statistics properly. Reshaping `df['mean]' isnt enought to assoicate a projected grid with the resulting zonal statistic calculations. Can you provide a link to the shapefile (ideally as geojson)?

    – dubbbdan
    Mar 26 at 17:35












  • @dubbbdan I added a link to the features which are hosted in a GitHub gist (gist.github.com/jbellino-usgs/6be521efec919c1ef5684e1452a069f9). The object returned by zonal_stats is a list of dicts with one dict for each zone feature in the grid shapefile. In this case each dictionary consists of one key and one value since I'm only asking for the mean. If I create a DataFrame from that list of dicts and then reshape the resulting column of data I end up with a numpy array with the same shape as the input grid features.

    – Jason Bellino
    Mar 26 at 18:26













0












0








0








BLUF::



I'm having trouble computing zonal statistics with a rotated array using the rasterstats package. I'm guessing the problem is with my affine matrix, but I'm not completely sure. Below is the affine transform matrix and output:



| 951.79, 0.45, 2999993.57|
| 0.00,-996.15,-1985797.84|
| 0.00, 0.00, 1.00|


enter image description here



Background:



I am creating files for a groundwater flow model and need to compute zonal statistics for each model grid cell using some .csv data from the Puerto Rico Agricultural Water Management web portal. These data are available on a daily timestep for numerous parameters (e.g. ET, tmax, tmin, precip, etc.). These files are not georeferenced, but ancillary files are available that specify the lon/lat for each cell which can then be projected using pyproj:



import pandas as pd
import numpy as np
import pyproj

url_base = 'http://academic.uprm.edu/hdc/GOES-PRWEB_RESULTS'

# Load some data
f = '/'.join([url_base, 'actual_ET', 'actual_ET20090101.csv'])
array = pd.read_csv(f, header=None).values

# Read longitude values
f = '/'.join([url_base, 'NON_TRANSIENT_PARAMETERS', 'LONGITUDE.csv'])
lon = pd.read_csv(f, header=None).values

# Read latitude values
f = '/'.join([url_base, 'NON_TRANSIENT_PARAMETERS', 'LATITUDE.csv'])
lat = np.flipud(pd.read_csv(f, header=None).values)

# Project to x/y coordinates (North America Albers Equal Area Conic)
aea = pyproj.Proj('+init=ESRI:102008')
x, y = aea(lon, lat)


Before I can compute zonal statistics, I need to create the affine transform that relates row/column coordinates to projected x/y coordinates. I specify the 6 parameters to create the Affine object using the affine library:



import math
from affine import Affine

length_of_degree_longitude_at_lat_mean = 105754.71 # 18.25 degrees via http://www.csgnetwork.com/degreelenllavcalc.html
length_of_degree_latitude_at_lat_mean = 110683.25 # 18.25 degrees via http://www.csgnetwork.com/degreelenllavcalc.html

# Find the upper left x, y
xul, yul = aea(lon[0][0], lat[0][0])
xll, yll = aea(lon[-1][0], lat[-1][0])
xur, yur = aea(lon[0][-1], lat[0][-1])
xlr, ylr = aea(lon[-1][-1], lat[-1][-1])

# Compute pixel width
a = abs(lon[0][1] - lon[0][0]) * length_of_degree_longitude_at_lat_mean

# Row rotation
adj = abs(xlr - xll)
opp = abs(ylr - yll)
b = math.atan(opp/adj)

# x-coordinate of the upper left corner
c = xul - a / 2

# Compute pixel height
e = -abs(lat[1][0] - lat[0][0]) * length_of_degree_latitude_at_lat_mean

# Column rotation
d = 0

# y-coordinate of the upper left corner
f = yul - e / 2

affine = Affine(a, b, c, d, e, f)


where:



  • a = width of a pixel

  • b = row rotation (typically zero)

  • c = x-coordinate of the upper-left corner of the upper-left pixel

  • d = column rotation (typically zero)

  • e = height of a pixel (typically negative)

  • f = y-coordinate of the of the upper-left corner of the upper-left pixel

(from https://www.perrygeo.com/python-affine-transforms.html)



The resulting affine matrix looks reasonable and I've tried passing row and column rotation as both radians and degrees with little change in the result. Link to grid features: grid_2km.geojson



import rasterstats
import matplotlib.pyplot as plt

grid_f = 'grid_2km.geojson'
gdf = gpd.read_file(grid_f)

zs = rasterstats.zonal_stats(gdf,
array,
affine=affine,
stats=['mean'])

df = pd.DataFrame(zs).fillna(value=np.nan)

fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(131, aspect='equal')
ax.pcolormesh(x, y, np.zeros_like(array))
ax.pcolormesh(x, y, array)
ax.set_title('Projected Data')

ax = fig.add_subplot(132, aspect='equal')
gdf.plot(ax=ax)
ax.set_title('Projected Shapefile')

ax = fig.add_subplot(133, aspect='equal')
ax.imshow(df['mean'].values.reshape((gdf.row.max(), gdf.col.max())))
ax.set_title('Zonal Statistics Output')

plt.tight_layout()
plt.show()


enter image description here



Further, there is a discrepancy between x, y value pairs transformed using the affine object versus those derived from the native lon, lat values using pyproj:



rr = np.array([np.ones(x.shape[1], dtype=np.int) * i for i in range(x.shape[0])])
cc = np.array([np.arange(x.shape[1]) for i in range(x.shape[0])])
x1, y1 = affine * (cc, rr)

fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(111, aspect='equal')
ax.scatter(x, y, s=.2)
ax.scatter(x1, y1, s=.2)

plt.show()


enter image description here










share|improve this question
















BLUF::



I'm having trouble computing zonal statistics with a rotated array using the rasterstats package. I'm guessing the problem is with my affine matrix, but I'm not completely sure. Below is the affine transform matrix and output:



| 951.79, 0.45, 2999993.57|
| 0.00,-996.15,-1985797.84|
| 0.00, 0.00, 1.00|


enter image description here



Background:



I am creating files for a groundwater flow model and need to compute zonal statistics for each model grid cell using some .csv data from the Puerto Rico Agricultural Water Management web portal. These data are available on a daily timestep for numerous parameters (e.g. ET, tmax, tmin, precip, etc.). These files are not georeferenced, but ancillary files are available that specify the lon/lat for each cell which can then be projected using pyproj:



import pandas as pd
import numpy as np
import pyproj

url_base = 'http://academic.uprm.edu/hdc/GOES-PRWEB_RESULTS'

# Load some data
f = '/'.join([url_base, 'actual_ET', 'actual_ET20090101.csv'])
array = pd.read_csv(f, header=None).values

# Read longitude values
f = '/'.join([url_base, 'NON_TRANSIENT_PARAMETERS', 'LONGITUDE.csv'])
lon = pd.read_csv(f, header=None).values

# Read latitude values
f = '/'.join([url_base, 'NON_TRANSIENT_PARAMETERS', 'LATITUDE.csv'])
lat = np.flipud(pd.read_csv(f, header=None).values)

# Project to x/y coordinates (North America Albers Equal Area Conic)
aea = pyproj.Proj('+init=ESRI:102008')
x, y = aea(lon, lat)


Before I can compute zonal statistics, I need to create the affine transform that relates row/column coordinates to projected x/y coordinates. I specify the 6 parameters to create the Affine object using the affine library:



import math
from affine import Affine

length_of_degree_longitude_at_lat_mean = 105754.71 # 18.25 degrees via http://www.csgnetwork.com/degreelenllavcalc.html
length_of_degree_latitude_at_lat_mean = 110683.25 # 18.25 degrees via http://www.csgnetwork.com/degreelenllavcalc.html

# Find the upper left x, y
xul, yul = aea(lon[0][0], lat[0][0])
xll, yll = aea(lon[-1][0], lat[-1][0])
xur, yur = aea(lon[0][-1], lat[0][-1])
xlr, ylr = aea(lon[-1][-1], lat[-1][-1])

# Compute pixel width
a = abs(lon[0][1] - lon[0][0]) * length_of_degree_longitude_at_lat_mean

# Row rotation
adj = abs(xlr - xll)
opp = abs(ylr - yll)
b = math.atan(opp/adj)

# x-coordinate of the upper left corner
c = xul - a / 2

# Compute pixel height
e = -abs(lat[1][0] - lat[0][0]) * length_of_degree_latitude_at_lat_mean

# Column rotation
d = 0

# y-coordinate of the upper left corner
f = yul - e / 2

affine = Affine(a, b, c, d, e, f)


where:



  • a = width of a pixel

  • b = row rotation (typically zero)

  • c = x-coordinate of the upper-left corner of the upper-left pixel

  • d = column rotation (typically zero)

  • e = height of a pixel (typically negative)

  • f = y-coordinate of the of the upper-left corner of the upper-left pixel

(from https://www.perrygeo.com/python-affine-transforms.html)



The resulting affine matrix looks reasonable and I've tried passing row and column rotation as both radians and degrees with little change in the result. Link to grid features: grid_2km.geojson



import rasterstats
import matplotlib.pyplot as plt

grid_f = 'grid_2km.geojson'
gdf = gpd.read_file(grid_f)

zs = rasterstats.zonal_stats(gdf,
array,
affine=affine,
stats=['mean'])

df = pd.DataFrame(zs).fillna(value=np.nan)

fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(131, aspect='equal')
ax.pcolormesh(x, y, np.zeros_like(array))
ax.pcolormesh(x, y, array)
ax.set_title('Projected Data')

ax = fig.add_subplot(132, aspect='equal')
gdf.plot(ax=ax)
ax.set_title('Projected Shapefile')

ax = fig.add_subplot(133, aspect='equal')
ax.imshow(df['mean'].values.reshape((gdf.row.max(), gdf.col.max())))
ax.set_title('Zonal Statistics Output')

plt.tight_layout()
plt.show()


enter image description here



Further, there is a discrepancy between x, y value pairs transformed using the affine object versus those derived from the native lon, lat values using pyproj:



rr = np.array([np.ones(x.shape[1], dtype=np.int) * i for i in range(x.shape[0])])
cc = np.array([np.arange(x.shape[1]) for i in range(x.shape[0])])
x1, y1 = affine * (cc, rr)

fig = plt.figure(figsize=(14, 6))

ax = fig.add_subplot(111, aspect='equal')
ax.scatter(x, y, s=.2)
ax.scatter(x1, y1, s=.2)

plt.show()


enter image description here







python numpy raster affinetransform rasterio






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 18:39







Jason Bellino

















asked Mar 22 at 20:07









Jason BellinoJason Bellino

2921516




2921516












  • If you have projected data and a projected shapefile, what makes you think its an affine issue? Are you using rasterstats?

    – dubbbdan
    Mar 26 at 13:19











  • @dubbbdan Yes, I'm using the rasterstats package; I've updated the question so that it now shows the zonal statistics computations. x, y values can be returned from the affine by passing row, column pairs and these x, y values do not match those computed directly from the native lon, lat pairs using pyproj which suggests to me that it's a problem with the affine. See the additional figure I added to the post to illustrate.

    – Jason Bellino
    Mar 26 at 17:13











  • rasterstats is a great package! The fact that zonal_stats returns data leads me to believe that everything is fine with you affine. Have you looked at passing the arguement raster_out=True in zonal_stats?

    – dubbbdan
    Mar 26 at 17:26











  • I think the problem is that you are not plotting the zonal statistics properly. Reshaping `df['mean]' isnt enought to assoicate a projected grid with the resulting zonal statistic calculations. Can you provide a link to the shapefile (ideally as geojson)?

    – dubbbdan
    Mar 26 at 17:35












  • @dubbbdan I added a link to the features which are hosted in a GitHub gist (gist.github.com/jbellino-usgs/6be521efec919c1ef5684e1452a069f9). The object returned by zonal_stats is a list of dicts with one dict for each zone feature in the grid shapefile. In this case each dictionary consists of one key and one value since I'm only asking for the mean. If I create a DataFrame from that list of dicts and then reshape the resulting column of data I end up with a numpy array with the same shape as the input grid features.

    – Jason Bellino
    Mar 26 at 18:26

















  • If you have projected data and a projected shapefile, what makes you think its an affine issue? Are you using rasterstats?

    – dubbbdan
    Mar 26 at 13:19











  • @dubbbdan Yes, I'm using the rasterstats package; I've updated the question so that it now shows the zonal statistics computations. x, y values can be returned from the affine by passing row, column pairs and these x, y values do not match those computed directly from the native lon, lat pairs using pyproj which suggests to me that it's a problem with the affine. See the additional figure I added to the post to illustrate.

    – Jason Bellino
    Mar 26 at 17:13











  • rasterstats is a great package! The fact that zonal_stats returns data leads me to believe that everything is fine with you affine. Have you looked at passing the arguement raster_out=True in zonal_stats?

    – dubbbdan
    Mar 26 at 17:26











  • I think the problem is that you are not plotting the zonal statistics properly. Reshaping `df['mean]' isnt enought to assoicate a projected grid with the resulting zonal statistic calculations. Can you provide a link to the shapefile (ideally as geojson)?

    – dubbbdan
    Mar 26 at 17:35












  • @dubbbdan I added a link to the features which are hosted in a GitHub gist (gist.github.com/jbellino-usgs/6be521efec919c1ef5684e1452a069f9). The object returned by zonal_stats is a list of dicts with one dict for each zone feature in the grid shapefile. In this case each dictionary consists of one key and one value since I'm only asking for the mean. If I create a DataFrame from that list of dicts and then reshape the resulting column of data I end up with a numpy array with the same shape as the input grid features.

    – Jason Bellino
    Mar 26 at 18:26
















If you have projected data and a projected shapefile, what makes you think its an affine issue? Are you using rasterstats?

– dubbbdan
Mar 26 at 13:19





If you have projected data and a projected shapefile, what makes you think its an affine issue? Are you using rasterstats?

– dubbbdan
Mar 26 at 13:19













@dubbbdan Yes, I'm using the rasterstats package; I've updated the question so that it now shows the zonal statistics computations. x, y values can be returned from the affine by passing row, column pairs and these x, y values do not match those computed directly from the native lon, lat pairs using pyproj which suggests to me that it's a problem with the affine. See the additional figure I added to the post to illustrate.

– Jason Bellino
Mar 26 at 17:13





@dubbbdan Yes, I'm using the rasterstats package; I've updated the question so that it now shows the zonal statistics computations. x, y values can be returned from the affine by passing row, column pairs and these x, y values do not match those computed directly from the native lon, lat pairs using pyproj which suggests to me that it's a problem with the affine. See the additional figure I added to the post to illustrate.

– Jason Bellino
Mar 26 at 17:13













rasterstats is a great package! The fact that zonal_stats returns data leads me to believe that everything is fine with you affine. Have you looked at passing the arguement raster_out=True in zonal_stats?

– dubbbdan
Mar 26 at 17:26





rasterstats is a great package! The fact that zonal_stats returns data leads me to believe that everything is fine with you affine. Have you looked at passing the arguement raster_out=True in zonal_stats?

– dubbbdan
Mar 26 at 17:26













I think the problem is that you are not plotting the zonal statistics properly. Reshaping `df['mean]' isnt enought to assoicate a projected grid with the resulting zonal statistic calculations. Can you provide a link to the shapefile (ideally as geojson)?

– dubbbdan
Mar 26 at 17:35






I think the problem is that you are not plotting the zonal statistics properly. Reshaping `df['mean]' isnt enought to assoicate a projected grid with the resulting zonal statistic calculations. Can you provide a link to the shapefile (ideally as geojson)?

– dubbbdan
Mar 26 at 17:35














@dubbbdan I added a link to the features which are hosted in a GitHub gist (gist.github.com/jbellino-usgs/6be521efec919c1ef5684e1452a069f9). The object returned by zonal_stats is a list of dicts with one dict for each zone feature in the grid shapefile. In this case each dictionary consists of one key and one value since I'm only asking for the mean. If I create a DataFrame from that list of dicts and then reshape the resulting column of data I end up with a numpy array with the same shape as the input grid features.

– Jason Bellino
Mar 26 at 18:26





@dubbbdan I added a link to the features which are hosted in a GitHub gist (gist.github.com/jbellino-usgs/6be521efec919c1ef5684e1452a069f9). The object returned by zonal_stats is a list of dicts with one dict for each zone feature in the grid shapefile. In this case each dictionary consists of one key and one value since I'm only asking for the mean. If I create a DataFrame from that list of dicts and then reshape the resulting column of data I end up with a numpy array with the same shape as the input grid features.

– Jason Bellino
Mar 26 at 18:26












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307096%2fcompute-zonal-statistics-for-a-numpy-array-in-rotated-coordinate-space%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55307096%2fcompute-zonal-statistics-for-a-numpy-array-in-rotated-coordinate-space%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현