0

I have created the following function to take Origin = str, Destination = str, line = shapely.geometry.linestring.LineString, node = GeoDataFrame

def create_lines_df(Origin, Destination, line_, nodes_):
    line_dfs = gpd.GeoDataFrame()
    dict_ = [{'Origin':Origin,'Destination':Destination,'geometry':line_,
                         'length':line_.length,
                       'osmid':[nodes_.index.values]}]
df = gpd.GeoDataFrame(dict_, geometry='geometry', crs=oslo_edges_proj.crs)
line_dfs = line_dfs.append(df, ignore_index=True)

and the goal is to return a geodataframe but the result geodataframe is empty, although when I change line_dfs to a list it does correctly return the result I want but in a list.

What do I need to change?

Edited the above code to be:

gamle_dfs = []
def create_lines_df_2(Origin, Destination, line_, nodes_):

dict_ = [{'Origin':Origin,'Destination':Destination,'geometry':line_, 'length':line_.length, 'osmid':[nodes_.index.values]}]

df = gpd.GeoDataFrame(dict_, geometry='geometry', crs=oslo_edges_proj.crs) gamle_dfs.append(df)

Now I have a list of dataframes that I can't extract. Any recommendations?

Ian Turton
  • 81,417
  • 6
  • 84
  • 185
  • 1
    You're not returning anything from your functions and you seem to be using global vars (bad practice) but not declaring them as global. Are you calling this function multiple times to try and build up a gdf iteratively? – user2856 Jan 01 '22 at 02:42
  • I am calling this function for each origin-destination couple, about 15 times for each district, as I need each district LineStrings together in 1 dataframe, any suggestions? – Kareem Alaraby Jan 01 '22 at 02:49
  • @user2856 yes this is what I am doing – Kareem Alaraby Jan 01 '22 at 14:32

1 Answers1

2

It's bad practice to modify globals inside your function and your function doesn't return anything.

  1. Inside your function, just create a single dataframe for the curent origin-destination couple and return it, i.e return df.
  2. Outside your function, append returned origin-destination couple DFs into a list (do not modify this list in your function) in a loop or using list comprehension.
  3. Concatenate the list of DFs, i.e df = gpd.GeoDataFrame(pd.concat(list_of_dfs, ignore_index=True))

You should also add a crs argument to your function and pass in oslo_edges_proj.crs rather than relying on a global (again, globals are bad ok)

user2856
  • 65,736
  • 6
  • 115
  • 196