Pandas - 使用apply()时,'Series'对象没有属性'colNames'

Run*_*ean 8 python pandas

我需要使用lambda函数来逐行计算.例如,创建一些数据帧

import pandas as pd
import numpy as np

def myfunc(x, y):
    return x + y

colNames = ['A', 'B']
data = np.array([np.arange(10)]*2).T

df = pd.DataFrame(data, index=[range(0, 10)], columns=colNames)
Run Code Online (Sandbox Code Playgroud)

使用'myfunc'这确实有效

df['D'] = (df.apply(lambda x: myfunc(x.A, x.B), axis=1))
Run Code Online (Sandbox Code Playgroud)

但这第二种情况不起作用!

df['D'] = (df.apply(lambda x: myfunc(x.colNames[0], x.colNames[1]), axis=1))
Run Code Online (Sandbox Code Playgroud)

给出错误

AttributeError: ("'Series' object has no attribute 'colNames'", u'occurred at index 0')
Run Code Online (Sandbox Code Playgroud)

我真的需要使用第二种情况(使用列表访问colNames),这会产生错误,有关如何执行此操作的任何线索?

谢谢

fog*_*rit 9

使用时df.apply(),DataFrame的每一行都将作为pandas Series传递给lambda函数.然后,框架的列将成为系列的索引,您可以使用series[label].

所以这应该工作:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 
Run Code Online (Sandbox Code Playgroud)