My question is simple. From geopy.distance
, I can calculate the distance between two points. But I can not transform the data format for further computation.
Code like this:
from geopy.distance import vincenty
length = vincenty((38.103414282108375, 114.51898800000002),\
(38.07902986076924, 114.50882128404997))
ration = np.array(([2,2],[3,3]))*length
Error:
unsupported operand type(s) for *: 'int' and 'vincenty'
I tried to change the Distance(xxx)
into np.array: np.array(length)
, but failed. It shows like array(Distance(388.659276576), dtype=object)
, still can't support for computation directly.
As suggested in the manual, you need to "export" your distance/vincenty in some format. E.g. like this:
> from geopy.distance import vincenty
> newport_ri = (41.49008, -71.312796)
> cleveland_oh = (41.499498, -81.695391)
> print(vincenty(newport_ri, cleveland_oh).miles)
538.3904451566326
You can not process vincenty
iteself, because (as you already mentioned) it is an object out of geopy that does not support mathematical operands. You need to extract the values inside the data object, e.g. with .miles
. See the full documentation for other possible values: GeoPy documentation
See the differences in types:
> type(vincenty(newport_ri, cleveland_oh))
geopy.distance.vincenty
> type(vincenty(newport_ri, cleveland_oh).miles)
float
Now you can calculate with this:
> vincenty(newport_ri, cleveland_oh).miles
538.3904451566326
> vincenty(newport_ri, cleveland_oh).miles * 2
1076.7808903132652
Or, if you really need a numpy array out of this:
> np.array(vincenty(newport_ri, cleveland_oh).miles)
array(538.3904451566326)
> type(np.array(vincenty(newport_ri, cleveland_oh).miles))
numpy.ndarray
EDIT: Note that you can even enforce it's data type with NumPy's built-in dtype
parameter:
> np.array(vincenty(newport_ri, cleveland_oh).miles, dtype=np.float32)
array(538.3904418945312, dtype=float32)
> np.array(vincenty(newport_ri, cleveland_oh).miles, dtype=np.float64)
array(538.3904451566326) # dtype=float64, default type here
> np.array(vincenty(newport_ri, cleveland_oh).miles, dtype=np.int32)
array(538, dtype=int32)
This could be helpful, if you're storing/loading lots of data but always just need a certain precision.