Python 将类方法应用于数据框的行

Con*_*nan 5 python vectorization pandas

我的类需要一行数据帧来构造一个对象,我想通过将 init 应用于数据帧的每一行来创建一个对象数组。有没有办法对其进行矢量化?我的班级定义看起来像

class A(object):
    def __init__(self,row):
        self.a = row['a']
        self.b = row['b']
Run Code Online (Sandbox Code Playgroud)

任何建议将不胜感激!

我有一种我不太满意的方法来解决这个问题。在类之外定义另一个函数,然后使用 apply。

def InitA(row):
    return A(row)
Run Code Online (Sandbox Code Playgroud)

假设 df 是我想用作参数的数据框。

xxx = df.apply(InitA,axis=1)
Run Code Online (Sandbox Code Playgroud)

给出我想要的。但是,我认为 InitA 没有必要。

我原来的问题有点复杂。类的定义是

class A(object):
    def __init__(self):
        return
    def add_parameter(self,row):
        self.a = row['a']
Run Code Online (Sandbox Code Playgroud)

我打算将 add_parameter 应用于数据框的每一行。但我认为定义另一个(lambda)函数对于解决这个问题是必要的。

McR*_*Rip 3

只使用 lambda 函数?

xxx = df.apply(lambda x: A(x),axis=1)

编辑:另一种解决方案是直接传递类,然后 apply-function 调用构造函数:

xxx = df.apply(A,axis=1)

这有效:

import pandas as pd 

class C(object):
    def __init__(self,dat):
        return

A = pd.DataFrame({'a':pd.Series([1,2,3])})
A.apply(lambda x: C(x),axis=1)
Run Code Online (Sandbox Code Playgroud)