簡體   English   中英

僅當滿足特定條件/計算時,如何使用 pandas/Python 對數據進行分組和聚合?

[英]How to group and aggregate data using pandas/Python only if a specific condition/calculation is met?

有一個 pandas.DataFrame df看起來像這樣:

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

我想按列CityCountry對數據進行分組並總結他們的人口:

grouped_data = df.groupby([df['City'], df['Country'])['Population'].agg('sum').reset_index()

但為了處理歧義——美國的兩個條目不會合並——我的想法是計算並檢查每個潛在groupby()結果的緯度/經度之間的距離。

假設有一個距離 function 以公里為單位返回兩個地理點的距離,我想按城市和國家對所有條目進行分組,並僅當distance()的結果小於 50 公里時才總結它們的人口。

上述示例的 output 可能如下所示:

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

知道如何在 pandas 中解決這個問題嗎? 我很高興你的建議。

您所要求的是一個網絡問題,如果兩個節點的距離小於 50 公里,則它們會被連接。 這樣做時,您可以創建一個距離矩陣並使用networkx構建圖形。 沿着這條線的東西:

from sklearn.metrics.pairwise import haversine_distances as haversine

# calculate haversine
dist_mat = haversine(np.deg2rad(df[['Latitude','Longitude']]) ) * 6371  # earth's radius

adjacency = dist_mat < 50

import networkx as nx
G = nx.from_numpy_matrix(adjacency)
components = nx.connected_components(G)

然后你可以對這些components進行分組

另一方面,您可能更容易允許在這些 bin 上合並 Lat/Long 和 groupby。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM