且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将函数应用于 pandas 数据框的每一行以创建两个新列

更新时间:2023-08-28 17:08:22

要使第一种方法可行,请尝试返回一个Series而不是一个元组(应用程序抛出异常,因为它不知道如何将行粘回去列数与原始框架不匹配).

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

具有:

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