1

I have a geopandas GeoDataframe representing the continental US states. I want to transform all the coordinates to a different coordinate system with non-trivial mapping.

My plan was to do something like (this is just a simple test, not the real transform):

from shapely.ops import transform
def id_func(x, y):
    return x-10, y

alabama = conus.iloc[0]
alabama.geometry = transform (id_func, alabama.geometry)

This doesn't work, the values of conus.geometry seem to be unchanged.

Any hints?

nbecker
  • 1,645
  • 5
  • 17
  • 23
  • I'm guessing that your GeoDataFrame does not have a single dtype, so alabama is a copy, not a view: https://stackoverflow.com/questions/47972633/in-pandas-does-iloc-method-give-a-copy-or-view – rcriii May 21 '19 at 19:11
  • I answered about the actual topic of transforming geometries, but on the "assign not working": setting to the geometry property should normally work, if you are assigning a list/array of geometries. In the code above you are assigning a single values, which should normally raise an error. You didn't get an error? – joris May 25 '19 at 13:41

2 Answers2

1

This code works:

from shapely.ops import transform
def touv (x, y):
    if type(x) is not float:
        raise TypeError
    return ll2UV (satlat, satlon, BSlat, BSlon, y, x)

for row in conus.index:
    conus.at[row,'geometry'] = transform (touv, conus.loc[row,'geometry'])

The key, it seems, is I needed to use '.at' to perform the assignment.

nbecker
  • 1,645
  • 5
  • 17
  • 23
0

The shapely.ops.transform function works on single geometries. For example (using your id_func function):

In [15]: from shapely.geometry import LineString

In [16]: from shapely.ops import transform

In [17]: l = LineString([(0, 0), (1, 1)])

In [18]: def id_func(x, y): 
    ...:     return x-10, y

In [20]: print(transform(id_func, l))
LINESTRING (-10 0, -9 1)

If you want to apply this to each geometry in a GeoSeries / GeoDataFrame, you will need to iterate trough them or apply the function:

new_geometries = [transform(id_func, geom) for geom in alabama.geometry]

BTW, if you are looking for ways to transforming geometries with custom functions, the affine transforms might be interesting: https://shapely.readthedocs.io/en/stable/manual.html#affine-transformations (and most of them are directly exposed on the GeoDataFrame / GeoSeries)

joris
  • 133,120
  • 36
  • 247
  • 202