import math from sklearn.neighbors import NearestNeighbors import numpy as np import pandas as pd k =4 df = pd.read_csv(r'C:\Users\bkalluri\Downloads\data_2.csv') predicted_list = [] for index, row in df.iterrows() : list1 = [] a = row.latitude b= row.longitude list1.append(a) list1.append(b) point1 = np.array(list1).reshape((1,2)) array1 = pd.DataFrame(df.loc[df['close_date']<row.close_date,['latitude','longitude','close_price']]).as_matrix() ''' Proceed only if an entry is found in the array. Array would be without any sample if there are no neighbours to any home. This happens for the home with minimum value of close date and without any duplicates. ''' if array1.shape[0] is not 0: ''' Checking the number of neighbours. If the neighbour count is < 4, then K is tightened to neighbours found. This is to accomodate the problem constraint. ''' if array1.shape[0] <= k : k = array1.shape[0] nbrs = NearestNeighbors(n_neighbors=k, algorithm='ball_tree').fit(array1[:,[0,1]]) distances, indices = nbrs.kneighbors(point1) distances = distances.reshape(k,) indices = indices.reshape(k,) prices = pd.Series(array1[:,2]) df2 = pd.DataFrame({'indices':indices,'distances':distances},index=indices) df2['ratio'] = np.exp(-df2['distances']) df2['weight'] = df2['ratio']/df2['ratio'].sum(axis=0) df2['prices'] = prices df2['estimate'] = df2['weight'] * df2['prices'] predicted_value = df2['estimate'].sum(axis=0) predicted_list.append(predicted_value) #print(predicted_value) ''' If the Home doesn't have any neighbour, the predicted value is considered to be none. ''' else : predicted_list.append(None) #print(len(df.index)) #print(len(predicted_list)) df['predicted_price'] = np.array(predicted_list) print(df)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question