2013-04-29 47 views
2

我遇到了用熊貓的數據框做空間分析的問題。現在我有一個DataFrame> 1000行,列「用戶」,「緯度」,「經度」。用熊貓做空間分析的有效方式

在此基礎上的數據集,我想去做一些空間分析,如創建第四列,其總結了在100公里範圍內的所有用戶。

有沒有辦法有效地做到這一點?

現在我用兩個for循環和geopy計算距離的方式如下:

df_geo['Neighbors'] = 0 

def getNeighbors(): 
    for i in df_geo.index: 
     p1 = (df_geo.ix[i]['latitude'], df_geo.ix[i]['longitude']) 
     count = 0 
     for i2 in df_geo.index: 
      p2 = Point (df_geo.ix[i2]['latitude'], df_geo.ix[i2]['longitude']) 
      if geopy.distance.distance(p1, p2).km < 100 & i != i2: 
       count += 1 
     df_geo.Neighbors[i] = count 



getNeighbors() 

謝謝

安迪

回答

3

我想我會做一個列的點objects:

df['point'] = df.apply(lambda row: Point(row['latitude'], row['longitude'])) 

然後做類似的事:

def neighbours_of(p, s): 
    '''count points in s within 100km radius of p''' 
    return s.apply(lambda p1: geopy.distance.distance(p, p1).km < 100).count() 

df['neighbours'] = df['points'].apply(lambda p: neighbours_of(p, df['points']) - 1) 
# the -1 ensures we don't include p in the count 

然而,一個內的應用仍然不會是特別有效的應用...