calculating result of a function for a column of a dataframe in python
<p>I am working on a dataframe in python to calculate the distance between a location and <code>LATITUDE</code> and <code>LONGITUDE</code> column in the dataframe.  When I run the code below, there is no error:</p>

<pre><code>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]))
</code></pre>

<p>but when I use the below one, there is an error </p>

<pre><code>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')))
</code></pre>

<p>and the error is:</p>

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

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

TypeError: a float is required
</code></pre>

<p>Because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow"><code>get_level_values</code></a> 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 <code>getDistanceBetween</code> doesn't know what to do with it.</p>

<p>Edit:
Now to compute it for all rows, we don't need any of the syntax fr above </p>

<pre><code># add the new column, initialized to NaN
dfTowers['distance'] = np.nan
for row_name, row in dfTowers.iterrows():
    row['distance'] = HL.getDistanceBetween(LCentroid, row['LATITUDE'], row['LONGITUDE'])
</code></pre>

python function pandas dataframe