2017-12-05 11 views
0

볼 트리에서 반경을 쿼리하여 데이터를 얻는 방법은 무엇입니까? 예를TypeError : unhashable type : 'numpy.ndarray'- 공 트리에서 반경을 쿼리하여 데이터 프레임에서 데이터를 가져 오는 방법은 무엇입니까?

from sklearn.neighbors import BallTree 
import pandas as pd 

bt = BallTree(df[['lat','lng']], metric="haversine") 

for idx, row in df.iterrow(): 
    res = df[bt.query_radius(row[['lat','lng']],r=1)] 

위해 나는 반경 r=1에 안양에서 해당 행을 싶어. 그러나 행

5183 
(5219, 25) 
5205 
(5219, 25) 
5205 
(5219, 25) 
5221 
(5219, 25) 
Traceback (most recent call last): 
    File "/Users/Chu/Documents/dssg2018/sa4.py", line 45, in <module> 
    df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\ 
IndexError: index 5221 is out of bounds for axis 0 with size 5219 

그리고 코드를 반복 할 때 내가 범위를 벗어난 인덱스를받은 첫 번째 대답 오류가 아닌

bag_of_words = ['beautiful','love','fun','sunrise','sunset','waterfall','relax'] 

for idx,row in df.iterrows(): 
    for word in bag_of_words: 
     if word in row['caption']: 
      df.loc[idx, word] = 1 
     else: 
      df.loc[idx, word] = 0 

bt = BallTree(df[['lat','lng']], metric="haversine") 
indices = bt.query_radius(df[['lat','lng']],r=(float(10)/40000)*360) 

for idx,row in df.iterrows(): 
    for word in bag_of_words: 
     if word in row['caption']: 
      print(idx) 
      print(df.shape) 
      df.loc[idx,word]=len(df.iloc[indices[idx]][df[word]==1])/\ 
          np.max([1,len(df.iloc[indices[idx]][df[word]!=1])]) 
+0

이 문서에 따르면, 외형 -.'bt.query_radius (행 [ "북", "LNG를 '] values.ravel()을, R = 1)' –

+0

@ cᴏʟᴅsᴘᴇᴇᴅ 아니요, 생성자에서 전달 된 것과 같은 2_D 배열이 필요합니다. –

+1

문제는 ndarray를 넣음으로써 행을 얻으려고합니까? 이 문제를 해결할 수있는 방법이 있습니까? – monotonic

답변

1

되는 다음과 같은 유형의 오류

TypeError: unhashable type: 'numpy.ndarray' 

를 던졌습니다 BallTree하지만 반환 된 인덱스는 인덱스에 넣기 위해 제대로 사용되지 않습니다.

for idx, row in df.iterrows(): 
    indices = bt.query_radius(row[['lat','lng']].values.reshape(1,-1), r=1) 
    res = df.iloc[[x for b in indices for x in b]] 
    # Do what you want to do with res 

(우리는 하나의 점 각 시간을 보내는 때문에)이도 할 것입니다 : 설명

res = df.iloc[indices[0]] 

을 :

내가 사용

은이 방법을 수행 0.20. 위에서 작성한 코드 :

df[bt.query_radius(row[['lat','lng']],r=1)] 

은 나를 위해 작동하지 않습니다. 나는 그것을 reshape()를 사용하여 2 차원 배열로 만들 필요가 있었다.

지금 the documentation에서 언급 한 바와 같이 지정된 반경 r 내에서 인덱스의 배열의 bt.query_radius() 반환 배열 :

ind : array of objects, shape = X.shape[:-1]

each element is a numpy integer array listing the indices of neighbors of the corresponding point. Note that unlike the results of a k-neighbors query, the returned neighbors are not sorted by distance by default.

그래서 우리는 데이터의 실제 지표에 도달하는 두 배열을 반복 할 필요가 있었다.

이제 우리는 인덱스를 얻었습니다. 팬더 데이터 프레임에서 iloc은 인덱스를 사용하여 데이터에 액세스하는 방법입니다.

업데이트 :

당신은 그나마은 bt에게 각각의 포인트마다 쿼리해야합니다. 모든 df을 한꺼번에 전송하여 반경 내에있는 색인의 색인이 포함 된 2 차원 배열을 해당 색인에 지정된 점까지 돌려 보낼 수 있습니다. 만약 포인트 1D 배열 전달되어야 같은

indices = bt.query_radius(df, r=1) 

for idx, row in df.iterrows(): 
    nearest_points_index = indices[idx] 
    res = df.iloc[nearest_points_index] 
    # Do what you want to do with res 
+0

왜 이것이 필요한지 설명해 줄 수 있습니까? – monotonic

+0

@monotonic 설명을 추가했습니다. 아직 명확하지 않은 경우 알려주십시오. –

+0

@monotonic 색인 범위 초과 오류와 관련하여 의견을 추가 한 것을 보았습니다. 그러나 내가이 페이지에 왔을 때 그 페이지가 없었습니다. 문제가 해결 되었습니까? –