我有两个数据框,比如说 dfr1 和 dfr2。dfr1 看起来像:
x,y,z
1,2,3
1,1,3
1,2,3
1,4,3
1,5,3
而 dfr2 看起来像:
p1,p2,p3
100,200,300
100,400,300
100,500,300
我想通过使用 dfr2 对 dfr1 的每一行应用一个过程。假设 dfr1 的每一行都是一些点的坐标。另一方面,dfr2 的列是我们可以称为“站”的其他点的坐标。对于 dfr1 的每个点,我想计算与 dfr2 的每个点的距离,以便对距离进行排序。
让我们定义功能测试:
import math
def test(rr):
res = math.sqrt((rr[0]-p1_x)**2 + (rr[1]-p1_y)**2 + (rr[2]-p_1z)**2)
return res
我已经学会了对 dfr1 的每一行应用测试:
res = dfr.apply(test, axis=1)
如何将 dfr2 的某些元素传递给函数。由于 dfr2 将具有更复杂的结构,我不想在函数内部阅读它。这是我的真实原始文件的示例,其中包含车站数据:
,station_1,station_3,station_3
coordiante x ,100,200,300
coordiante y ,100,400,300
coordiante z ,100,500,300
2018-01-01 00:00:00 ,1,2,3
2018-01-01 01:00:00 ,2,2,3
2018-01-01 02:00:00 ,3,2,3
2018-01-01 03:00:00 ,4,2,3
2018-01-01 04:00:00 ,4,NaN,3
2018-01-01 05:00:00 ,3,2,3
我在stackoverflow的另一篇文章中找到了这个解决方案:
def func(x, other):
other_value = other.loc[x.name]
return your_actual_method(x, other_value)
result = df1.apply(lambda x: func(x, df2))
由于我一次只使用一行,我将其修改为
def func(x, other):
other_value = other.loc[x.name]
return your_actual_method(x, other_value)
for i in range (4,13)
result = df1.iloc[0:5].apply(lambda x: func(x, df2.iloc[0:3],df2.iloc[i]),axis=1)
我确实喜欢这样一个事实,即我必须将它插入循环中,以便将每个步骤传递给函数的不同行。我有点担心计算速度。你怎么看?