Apply function to each row of pandas dataframe to create two new columns

To make the first approach work, try returning a Series instead of a tuple (apply is throwing an exception because it doesn’t know how to glue the rows back together as the number of columns doesn’t match the original frame).

def calculate(s):
    a = s['path'] + 2*s['row'] # Simple calc for example
    b = s['path'] * 0.153
    return pd.Series(dict(col1=a, col2=b))

The second approach should work if you replace:

st.ix[i]['a'] = a

with:

st.ix[i, 'a'] = a

Leave a Comment