计算位置数据

时间:2017-02-24 17:10:19

标签: python pandas

我有足球运动员位置数据。现在我必须计算从玩家A到数据集中其他玩家B,C,D的距离,并根据它们的接近顺序排列列。数据看起来像这样

ts1 = np.random.rand(10)
ts2 = np.random.rand(10)
ts3 = np.random.rand(10)
ts4 = np.random.rand(10)
ts5 = np.random.rand(10)
ts6 = np.random.rand(10)
ts7 = np.random.rand(10)
ts8 = np.random.rand(10)
d = {'A_x': ts1, 'A_y': ts2,'B_x': ts3, 'B_y':ts4, 'C_x':ts5, 'C_y':ts6,
                         'D_x':ts7, 'D_y':ts8}
df = pd.DataFrame(data=d)

所以数据看起来像这样 DF

A_x       A_y       B_x       B_y       C_x       C_y       D_x  \

0 0.423073 0.980156 0.513101 0.842604 0.196775 0.482592 0.419169
1 0.363428 0.520050 0.799685 0.184905 0.919634 0.483978 0.313876
2 0.029975 0.010020 0.739184 0.443437 0.884022 0.328365 0.448889
3 0.674032 0.399175 0.512700 0.697177 0.414588 0.915752 0.095993
4 0.962292 0.939266 0.466896 0.406284 0.922713 0.405991 0.798676
5 0.929178 0.936950 0.886348 0.639929 0.518401 0.848468 0.985375
6 0.290297 0.398941 0.896976 0.775312 0.976815 0.546444 0.937562
7 0.332582 0.191384 0.075902 0.645477 0.433419 0.917658 0.850850
8 0.817298 0.612915 0.903426 0.662707 0.825628 0.648411 0.556697
9 0.383350 0.715573 0.994297 0.491445 0.785036 0.110449 0.072658

    D_y  

0 0.909314
1 0.235216
2 0.284318
3 0.022496
4 0.756945
5 0.772382
6 0.850470
7 0.586915
8 0.799697
9 0.391556

所以第一个问题是我如何计算每对柱的距离?所以输出应该有3列,如: A-B A-C A-D 第二个问题是我如何生成一个新的位置表,对于每一行,列将按它们与A的接近程度排序。因此新表将具有列 A_x A_y nearest1st_X nearest1st_y nearest2nd_x nearest2nd_y nearest3d_x nearest3d_y 感谢

1 个答案:

答案 0 :(得分:0)

你可以使用numpy.linalg.norm:

dist = numpy.linalg.norm(a-b)

或者SciPy中有一个函数,它叫做Euclidean

from scipy.spatial import distance
a = (1,2,3)
b = (4,5,6)
dst = distance.euclidean(a,b)

并将其包含在循环中以读取每列

编辑:

这可能不是最好的方式,而是一个例子:

import numpy as np

num_P=10
ts1 = np.random.rand(num_P)
ts2 = np.random.rand(num_P)
ts3 = np.random.rand(num_P)
ts4 = np.random.rand(num_P)
ts5 = np.random.rand(num_P)
ts6 = np.random.rand(num_P)
ts7 = np.random.rand(num_P)
ts8 = np.random.rand(num_P)
d = {'A_x': ts1, 'A_y': ts2,'B_x': ts3, 'B_y':ts4, 'C_x':ts5, 'C_y':ts6,
                         'D_x':ts7, 'D_y':ts8}
f={}
for i in range(num_P):
    print i
    nkey="postion "+ str(i)
    f[nkey]=[]
    position=[item[i] for item in d.values()]
        for n,k in enumerate(position[:-1]): 
        a=position[n]
        b=position[n+1]         
        dist = np.linalg.norm(a-b)
        f[nkey].append(dist)
相关问题