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

后端 未结 4 1827
小蘑菇
小蘑菇 2020-12-02 14:36

I have a pandas DataFrame, st containing multiple columns:


DatetimeIndex: 53732 entries, 1993-01-0         


        
4条回答
  •  春和景丽
    2020-12-02 14:53

    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
    

提交回复
热议问题