如何使用Apply将列作为参数传递给类

邪恶的世界
class Movie:

    def __init__(self, title, imdb, critic, quote):
        self.title = title
        self.imdb = imdb
        self.critic = critic
        self.quote = quote

    def mashup(self):    
        x =self.title + self.imdb + self.critic + self.quote
        return self.x

df['concat'] = df.apply(Movie,axis=1)

我希望看到的结果是将每一列连接为数据帧中的新列。

问题是Movie没有收到预期的参数数量,我没有调用mashup方法,但不确定出什么问题。

TypeError: ("__init__() missing 3 required positional arguments: 'imdb', 'critic', and 'quote'", 'occurred at index 0')
pp

通常,直接分配计算的序列是清晰有效的。如果希望将显式函数用于pipe逐级计算,则将数据框添加到函数:

df = pd.DataFrame(np.arange(15).reshape((5, 3)))

def summer(x):
    return x[0] + x[1] + x[2]

df['sum_1'] = df[0] + df[1] + df[2]
df['sum_2'] = df.pipe(summer)

print(df)

    0   1   2  sum_1  sum_2
0   0   1   2      3      3
1   3   4   5     12     12
2   6   7   8     21     21
3   9  10  11     30     30
4  12  13  14     39     39

通常不需要将各个列传递给您的函数。什么是推荐的是通过一个Python级逐行循环apply

df['sum_3'] = df.apply(lambda x: x[0] + x[1] + x[2], axis=1)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章