pandas Dataframe columns doing algorithm
<p>I have a dataframe like this:</p>

<pre><code>df = pd.DataFrame({
    'A': ['a', 'a', 'a', 'a', 'a'],
    'lon1': [128.0, 135.0, 125.0, 123.0, 136.0],
    'lon2': [128.0, 135.0, 139.0, 142.0, 121.0],
    'lat1': [38.0, 32.0, 38.0, 38.0, 38.0],
    'lat2': [31.0, 32.0, 35.0, 38.0, 29.0],
    'angle': [0, 0, 0, 0, 0]
})
</code></pre>

<p>I want to count the angle of each row by this function and save back to the angle column</p>

<pre><code>def angle(lon1,lat1,lon2,lat2):
    dx = lon2 - lon1
    dy = lat2 - lat1
    direction = 0;
    if ((dx == 0) &amp; (dy == 0)):  # same position
    return direction
    if (dx &gt; 0.0) :    
        direction = 90-np.arctan2(dy,dx)*180/np.pi
    elif (dy &gt; 0.0 ) :    
        direction = 180+(270-(np.arctan2(dy,dx)*180/np.pi))
    else :   
        direction = 360-(270+(np.arctan2(dy,dx)*180/np.pi))
        if (direction &lt; 0) :
            direction += 360

    return (direction.astype(int) % 360)  
</code></pre>

<p>I tried </p>

<pre><code>df.ix[df['A'].notnull(), 'angle'] =angle(
    df[df['A'].notnull()]['lon1'],
    df[df['A'].notnull()]['lat1'],
    df[df['A'].notnull()]['lon2'], 
    df[df['A'].notnull()]['lat2']) 
</code></pre>

<p>and I got an error</p>

<blockquote>
  <p>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().</p>
</blockquote>

<p>I tried <code>for index,row in df.iterrows():</code> the result of for loop is ok but it took terribly long long time(original data is about 10 million rows ) </p>

<p>could anyone kindly give some efficient methods?</p>

<p>I'm sure there's a more vectorized solution, but here is a solution using the row-wise version of the <code>apply</code> method, which only slightly alters your function:</p>

<pre><code>def angle(row):
    dx = row.lon2 - row.lon1
    dy = row.lat2 - row.lat1
    direction = 0;
    if ((dx == 0) &amp; (dy == 0)):  # same position
        return direction
    if (dx &gt; 0.0) :    
        direction = 90-np.arctan2(dy,dx)*180/np.pi
    elif (dy &gt; 0.0 ) :    
        direction = 180+(270-(np.arctan2(dy,dx)*180/np.pi))
    else :   
        direction = 360-(270+(np.arctan2(dy,dx)*180/np.pi))
    if (direction &lt; 0) :
        direction += 360

    return (direction.astype(int) % 360)  

df['angle'] = df.apply(angle, axis=1)
</code></pre>

<p>Output:</p>

<pre><code>    A   angle   lat1    lat2    lon1    lon2
0   a   180     38.0    31.0    128.0   128.0
1   a   0       32.0    32.0    135.0   135.0
2   a   102     38.0    35.0    125.0   139.0
3   a   90      38.0    38.0    123.0   142.0
4   a   239     38.0    29.0    136.0   121.0
</code></pre>

python pandas