Nov-24-2020, 02:06 PM
(This post was last modified: Nov-24-2020, 04:27 PM by dvazquezgu.)
I have three dictionaries with coordinates looking like this:
First one
So far, I've been able to do it for a single crime with these lines of code:
First Line of Code:
First one
one_crime_cord
Containing a unique crime(34.0141, -118.2978)Second one
crime_cord
Containing multiple crimes{0: (34.0141, -118.2978), 1: (34.0459, -118.2545), 2: (34.1847, -118.44)}Third one
neigh_cord
Containing multiple neighborhoods{'Acton': (34.497355239240854, -118.1698101922935), 'Adams-Normandie': (34.03146149912416, -118.30020800000014), 'Agoura Hills': (34.146736499122795, -118.75988450000015)}I am trying to set a nested loop to get the distances from every crime to every neighborhood, and then input on an external data frame the neighborhood each crime belongs to based on the minimum distance.
So far, I've been able to do it for a single crime with these lines of code:
First Line of Code:
d3=[] n_name=[] for neigh_name, coord in neigh_cord.items(): d2=distance (one_crime_coord,coord).m n_name.append(neigh_name) d3.append(d2) print(neigh_name,d2)Output:
Acton 54886.9994821537 Adams-Normandie 1938.5858465073106 Agoura Hills 45115.60137307561Second Line of Code:
distan_df=pd.DataFrame() distan_df['Neighborhood_Name']=n_name; distan_df['Distance to Crime']=d3 print(min(d3)) distan_df index_min = np.argmin(d3) print('------') print('The Crime was commited in the neighborhood:') print(distan_df.iloc[index_min,0])Output:
472.2815720091788 ------ The Crime was commited in the neighborhood: Exposition ParkThird Line of Code:
test=la_crime_refined.copy() test['Neighborhood']='' test.head() test.at[index_min,'Neighborhood']= distan_df.iloc[index_min,0] display(test.iloc[index_min])With the output in the data frame I'm trying to populate of:
Neighborhood 83 Exposition ParkI figured I could do something similar using a nested loop:
distan_matrix=pd.DataFrame() n_name2=[] d5=[] for crime_no,crime_cord in crime_cord.items(): for neigh_name, coord in neigh_cord.items(): d4=distance (crime_cord,coord).m n_name2.append(neigh_name) d5.append(d4) distan_matrix=pd.DataFrame() distan_matrix['Neighborhood_Name']=n_name2; distan_matrix['Distance to Crime']=d4 index_min = np.argmin(d4) test.at[index_min,'Neighborhood']= distan_matrix.iloc[index_min,0] print('------') print('All Crimes have been assigned to a neighborhood') test.head()**The desired output would be a filled 'Neighborhood' column in
test
df**Neighborhood 1 North Holywood 2 Woodland Hills 3 Topanga Canyon . . . 83 Exposition Park . . .However, I am not able to make it work. Is it because I'm using the outer loop variable in the inner loop? any suggestions? This is the error I'm obtaining:
File "<ipython-input-57-8379f4221588>", line 4 for crime_no,crime_cord in crime_cord.items() ^ SyntaxError: invalid syntaxThank you and sorry for the length of the question!