Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将函数按行应用于数据帧_Python_Pandas_Function_Apply - Fatal编程技术网

Python 将函数按行应用于数据帧

Python 将函数按行应用于数据帧,python,pandas,function,apply,Python,Pandas,Function,Apply,我必须从二维坐标计算希尔伯特曲线上的距离。使用hilbertcurve包,我构建了自己的“hilbert”函数。坐标存储在数据帧(列1和列2)中。如您所见,我的函数在应用于两个值(test)时有效 但是,当通过应用函数按行应用时,它不起作用!为什么会这样?我做错了什么?我需要一个额外的列“hilbert”,其中hilbert距离x坐标和y坐标在列“col_1”和“col_2”中给出 最后一个命令以错误结束: The truth value of a Series is ambiguous. Us

我必须从二维坐标计算希尔伯特曲线上的距离。使用hilbertcurve包,我构建了自己的“hilbert”函数。坐标存储在数据帧(列1和列2)中。如您所见,我的函数在应用于两个值(test)时有效

但是,当通过应用函数按行应用时,它不起作用!为什么会这样?我做错了什么?我需要一个额外的列“hilbert”,其中hilbert距离x坐标和y坐标在列“col_1”和“col_2”中给出

最后一个命令以错误结束:

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

谢谢你的帮助

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

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

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

您必须将轴定义为1,因为您希望将函数应用于行,而不是列

您可以定义一个lambda函数,以便仅对两行应用hilbert,如下所示:

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

谢谢您的回答,但是当用您的解决方案替换最后一行时:df[“hilbert”]=df.apply(lambda x:hilbert(x[“col_1”]、x[“col_2”]、axis=0),它说的是KeyError:(“col_1”,“发生在索引ID处”)注意到您在axis=0应该是
axis=1
的时候注意到了。啊,现在我明白了!非常感谢。
df['hilbert'] = df.apply(lambda row: hilbert(row['col_1'], row['col_2']), axis=1)