调试Pandas数据框应用

3 投票
1 回答
4137 浏览
提问于 2025-04-18 00:00

我刚接触Pandas,有个问题想请教:我想把我自己写的函数my_func应用到数据表的每一行。

res = df.apply(lambda x: my_func(x, par1, par2)

当我调试的时候,在我定义的函数的第一行设置了一个断点:

def my_func(myinput, par1):
    (...)

如果我查看我的输入变量myinput,我会发现它包含了整个数据表(df)。我本来只想看到df的第一行,难道我漏掉了什么吗?

非常感谢

祝好

1 个回答

3

你需要在 apply 里设置 axis=1

res = df.apply(lambda x: my_func(x, par1, par2), axis=1)

在线文档提到,axis=0 是按列操作,而 axis=1 是按行操作。

你也可以直接传入这一行:

res = df.apply(lambda row: my_func(row), axis=1)

然后重新定义你的函数:

def my_func(row):
    # do something with col1
    row['col1'] = row['col1'] * 2
    row['col2'] = row['col2'] + 2
    # .... etc

撰写回答