将功能按行应用于熊猫数据框

垃圾场

我必须根据2D坐标计算希尔伯特曲线上的距离。为此,我使用hilbertcurve程序包构建了自己的“ hilbert”功能。坐标存储在数据框中(col_1和col_2)。如您所见,我的函数在应用于两个值(测试)时有效。

但是,当通过apply-function逐行应用时,它不起作用!为什么是这样?我在这里做错了什么?我需要一个额外的列“ hilbert”,其在列“ 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().

感谢您的帮助!

兰迪

由于您已hilbert(df.col_1, df.col_2)在应用中,因此立即尝试使用pd.Series这两列的完整es来调用函数,从而触发该错误。您应该做的是:

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

因此给定的lambda函数将应用于每一行。

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章