Calculating Distance between 2 column coordinates

64 Views Asked by At

I am trying to create a distance matrix so am trying to calculate distances between coordinates across a column. I've tried to use the following but it keeps throwing me an error

**"ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."**

I've been trying to solve this but i cannot seem to find an answer. Can someone help me understand it please?

def distancer(row):
    coords_1 = (row_df['lat'], row_df['lng'])
    col_coord = row_df.iloc[j,6],row_df.iloc[j,5]
    return geopy.distance.geodesic(col_coord, coords_1).kilometers


temp = geo_data[geo_data['NACE_2dgt']=='27']
dist_matrix = pd.DataFrame([], index=temp.index, columns=temp.index)
dist_matrix_list = dist_matrix.index

target_df = pd.DataFrame(dist_matrix.index)
target_df=target_df.reset_index()
target_df=target_df.rename(columns={'index':'index_col',0:'firm_id'})
row_df = pd.merge(left=target_df,right=geo_data,on='index_col')
a = dist_matrix.apply(distancer, axis=1, result_type='expand')

I was hoping to get a column of distances between the 2 coordinates.

1

There are 1 best solutions below

0
On

The error you encountered 'ValueError: The truth value of a Series is ambiguous,' typically occurs when you try to use a pandas DataFrame or Series in a boolean context, such as in an if statement. In your case it seems like the issue arises from how you are trying to access values from the DataFrame.

When working with pandas DataFrames, it's important to use [ .loc or .iloc ] to access specific elements. In your distancer function you should use row['lat'] andd row['lng'] instead of row_df['lat'] and row_df['lng']. This ensures that you are accessing the values of the current row.

Make sure that the row_df DataFrame is properly defined and contains the required columns. The error may also occur if the DataFrame structure is not as expected.By making these adjustments, you should be able to calculate distances between coordinates across a column successfully.