Created
November 17, 2021 15:18
-
-
Save afcotroneo/169f91404e9d98aee54a8351559221d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
seed = 10 | |
s=RandomState(seed) if seed else RandomState(seed) | |
def gen_random_points_poly(poly, num_points): | |
""" | |
Returns a list of N randomly generated points within a polygon. | |
""" | |
min_x, min_y, max_x, max_y = poly.bounds | |
points = [] | |
i=0 | |
while len(points) < num_points: | |
random_point = Point([s.uniform(min_x, max_x), s.uniform(min_y, max_y)]) | |
if random_point.within(poly): | |
points.append(random_point) | |
i+=1 | |
return points | |
def gen_points_in_gdf_polys(geometry, values, points_per_value = None): | |
""" | |
Take a GeoSeries of Polygons along with a Series of values and returns randomly generated points within | |
these polygons. Optionally takes a "points_per_value" integer which indicates the number of points that | |
should be generated for each 1 value. | |
""" | |
if points_per_value: | |
new_values = (values/points_per_value).astype(int) | |
else: | |
new_values = values | |
new_values = new_values[new_values>0] | |
if(new_values.size > 0): | |
g = gpd.GeoDataFrame(data = {'vals':new_values}, geometry = geometry) | |
a = g.apply(lambda row: tuple(gen_random_points_poly(row['geometry'], row['vals'])),1) | |
b = gpd.GeoSeries(a.apply(pd.Series).stack(), crs = geometry.crs) | |
b.name='geometry' | |
return b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment