There is a pandas.DataFrame df
that looks like this:
City Country Latitude Longitude Population ...
Berlin Germany 52.516602 13.304105 118704
Berlin Germany 52.430884 13.192662 292000
...
Berlin USA 39.7742446 -75.0013423 7588
Berlin USA 43.9727912 -88.9858084 5524
I would like to group data by columns City
and Country
and sum up their population:
grouped_data = df.groupby([df['City'], df['Country'])['Population'].agg('sum').reset_index()
But in order to handle ambiguity – the two entries for USA are not to be merged –, my idea was to calculate and check the distance between lat/long for every potential groupby()
-result.
Assuming to have a distance function that returns the distance of two geographic points in kilometres, I'd like to group all entries by City and Country and sum up their population only if the result of distance()
is e.g. less than 50 kilometres.
The output for the example above could look like:
City Country Latitude Longitude Population
Berlin Germany [52.516602, 52.430884] [13.304105, 13.192662] 410704
...
Berlin USA 39.7742446 -75.0013423 7588
Berlin USA 43.9727912 -88.9858084 5524
Any idea how to solve this in pandas? I am happy for your suggestions.