Selecting in DataFrame without typing 'INDEX', but by calling user-defined variable as existing index/value

Viewed 62

I'm looking for a way to select a specific part of a DataFrame. This works as follows:

df = gpd.read("path_to_file")

df.set_index(['OBJECTID'], inplace=True)

Polygon = df.loc[['81207'], 'geometry']

(the code continues with other operations using the same 'OBJECTID' in different GeoDataFrame; this is needed to not lose geometry of points and/or polygons as only one geometry type can be linked to a GeoDataFrame)

This gives the correct output. However, the same process will be incorporated in a function to receive similar output for a user-defined input of the 'OBJECTID'. I'm therefore looking for a way to select data based on a user-defined variable: OBJECTID = 81207. How can an index be called by using a variable?

Any suggestions are welcome.

Thanks in advance.

Example of what I would like to achieve:

def Building(OBJECTID):
    OBJECTID = OBJECTID
    print("Building with OBJECTID:", OBJECTID)
    Polygon = df.loc['OBJECTID'] #OBJECTID defined in function
    Points = df2.loc['OBJECTID'] #OBJECTID defined in function
    return (Polygon, Points)
1 Answers

SOLVED:

This can be done by formatting the variable as a string.

def Building(OBJECTID):
    print("Building with ObjectID:", OBJECTID)
    Polygon = df.loc['{}'.format(OBJECTID)]
    Points = df2.loc['{}'.format(OBJECTID)]
    return Polygon, Points

Hope this is helpful for others.

Related