将函数按行应用到pandas数据框中。

问题描述 投票:1回答:2

我必须从二维坐标计算希尔伯特曲线上的距离。我用hilbertcurve-package建立了我自己的 "希尔伯特 "函数来计算。坐标被存储在一个数据框中(col_1和col_2)。正如你所看到的,我的函数在应用于两个值(测试)时可以工作。

然而,当通过apply-function应用于行时,它却不能工作!这是为什么?我到底做错了什么?我需要一个额外的列 "希尔伯特",列 "col_1 "和 "col_2 "中给出的x和y坐标的希尔伯特距离。

import pandas as pd
from hilbertcurve.hilbertcurve import HilbertCurve

df = pd.DataFrame({'ID': ['1', '2', '3'],
                   'col_1': [0, 2, 3],
                   'col_2': [1, 4, 5]})


def hilbert(x, y):
    n = 2
    p = 7
    hilcur = HilbertCurve(p, n)
    dist = hilcur.distance_from_coordinates([x, y])
    return dist


test = hilbert(df.col_1[2], df.col_2[2])

df["hilbert"] = df.apply(hilbert(df.col_1, df.col_2), axis=0)

最后一条命令以错误结束。

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

谢谢你的帮助!

python pandas function apply
2个回答
1
投票

由于你有 hilbert(df.col_1, df.col_2) 中的应用,这就是立即尝试调用你的函数与完整的 pd.Series这两列的es,引发了该错误。你应该做的是

df.apply(lambda x: hilbert(x['col_1'], x['col_2']), axis=1)

这样给出的lambda函数就会被应用到每一行。


0
投票

你必须将你的轴定义为1,因为你想将你的函数应用于行,而不是列。

你可以像这样定义一个lambda函数,只对两行应用希尔伯特。

df['hilbert'] = df.apply(lambda row: hilbert(row['col_1'], row['col_2']), axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.