在pandas dataframe python上应用成对函数

时间:2018-01-24 12:30:42

标签: python distance pairwise

我有一个数据帧,我想成对地应用我自己的距离。 问题是myDistance需要2个数据帧,并且使用skelarn pairwise_distance或scipy pdist转换为ndarray。 例如:

df = pd.DataFrame([[1,2,3,3],[2,3,3,4],[4,1,3,2]],columns=['A','B','C','D'])

返回:

    A   B   C   D
0   1   2   3   3
1   2   3   3   4
2   4   1   3   2

然后:

def myDistance(f1,f2):
    return f1['A']-f2['A']

myDistance(df.loc[0],df.loc[1])

这可以工作并返回-1。
但这不是,因为pdist将df行视为ndarray

from scipy.spatial.distance import pdist
dist = pdist(df,myDistance)

IndexError:只有整数,切片(:),省略号(...),numpy.newaxis(None)和整数或布尔数组才是有效索引

1 个答案:

答案 0 :(得分:0)

我认为我理解你的问题。您希望基本上仅在数据框的A列上计算成对距离。在这种情况下,假设列A是两个数据帧的第一列,那么您希望将自定义函数更改为:

def myDistance(u, v):
    return((u - v)[0])  # get the 0th index, which corresponds to column A

现在运行:

dist = pdist(df, myDistance)

结果:

array([-1., -3., -2.])