user3854325 user3854325 - 1 year ago 50
Python Question

calculating result of a function for a column of a dataframe in python

I am working on a dataframe in python to calculate the distance between a location and

column in the dataframe. When I run the code below, there is no error:

lLat= 43.679194
lLon= -79.633352
LCentroid= (lLat, lLon)
# getDistanceBetween gets two centroids and calculate the distance
dfTowers['distance']= HL.getDistanceBetween(LCentroid, dfTowers.index.get_level_values('LATITUDE')[0], dfTowers.index.get_level_values('LONGITUDE')[0]))

but when I use the below one, there is an error

lLat= 43.679194
lLon= -79.633352
LCentroid= (lLat, lLon)

dfTowers['distance']= HL.getDistanceBetween(LCentroid, dfTowers.index.get_level_values('LATITUDE'), dfTowers.index.get_level_values('LONGITUDE')))

and the error is:

TypeError Traceback (most recent call last)
<ipython-input-43-065640ee0e20> in <module>()
6 dfTowers['distance']= HL.getDistanceBetween(LCentroid, (dfTowers.index.get_level_values('LATITUDE'),
----> 7 dfTowers.index.get_level_values('LONGITUDE')))

C:\Users\x190523\Documents\python exercice\HomeLocation.pyc in getDistanceBetween(c1, c2)

TypeError: a float is required

Answer Source

Because get_level_values return a "vector" of labels. In your first example, you access the vector and appropriately retrieve the value. In your second example, you pass the entire vector and getDistanceBetween doesn't know what to do with it.