使用自定义功能将熊猫数据框中的人分组

时间:2020-03-23 19:54:54

标签: python pandas dataframe grouping distance

简介: 我有一个熊猫数据框,其中包含生活在不同位置(纬度,经度,楼层号)的人。我想将3个人组成一个小组。这意味着,在此过程结束时,每个人都被分配到一个特定的组。我的数据框的长度是9的倍数(例如18个人)。

棘手的部分是,同一组中的人在纬度和经度上不允许位于相同的位置。

出了什么问题? 将函数应用于pandas数据框后,将得到一个新的数据框,其中将人员分配到了组。但是,有两个问题:

1)每次 not 未将3个人分配到一个组!我不知道为什么,也不知道这是我第二个问题的原因。

2)由于某些原因(我不清楚),将位置(纬度/经度)相同的人归为一类!请记住,这永远都不会发生。

这是我所做的:

(链接到Google Colab

导入库:

from math import atan2, cos, radians, sin, sqrt
import math
import pandas as pd
import numpy as np
from random import random

获取数据:

array_data=([[ 50.56419  ,   8.67667  ,   2.       , 160.       ],
   [ 50.5740356,   8.6718179,   1.       ,   5.       ],
   [ 50.5746321,   8.6831284,   3.       , 202.       ],
   [ 50.5747453,   8.6765588,   4.       , 119.       ],
   [ 50.5748992,   8.6611471,   2.       , 260.       ],
   [ 50.5748992,   8.6611471,   3.       , 102.       ],
   [ 50.575    ,   8.65985  ,   2.       , 267.       ],
   [ 50.5751   ,   8.66027  ,   2.       ,   7.       ],
   [ 50.5751   ,   8.66027  ,   2.       ,  56.       ],
   [ 50.57536  ,   8.67741  ,   1.       , 194.       ],
   [ 50.57536  ,   8.67741  ,   1.       , 282.       ],
   [ 50.5755255,   8.6884584,   0.       , 276.       ],
   [ 50.5755273,   8.674282 ,   3.       , 167.       ],
   [ 50.57553  ,   8.6826   ,   2.       , 273.       ],
   [ 50.5755973,   8.6847492,   0.       , 168.       ],
   [ 50.5756757,   8.6846139,   4.       , 255.       ],
   [ 50.57572  ,   8.65965  ,   0.       ,  66.       ],
   [ 50.57591  ,   8.68175  ,   1.       , 187.       ]])

all_persons = pd.DataFrame(data=array_data) # convert back to dataframe

all_persons.rename(columns={0: 'latitude', 1: 'longitude', 2:'floor', 3:'id'}, inplace=True) # rename columns

此功能用于计算人与人之间的距离。如果距离等于0,则人们在纬度和经度上的位置相同。

def calculate_distance(lat1, lon1, lat2, lon2, floor_person_1, floor_person_2):
    """
    Calculate the shortest distance between two points given by the latitude and
    longitude.
    """
    scattering_factor = 0.0001

    earth_radius = 6373  # Approximate / in km.
    lat1 = radians(lat1)
    lon1 = radians(lon1)
    lat2 = radians(lat2)
    lon2 = radians(lon2)

    dlon = lon2 - lon1
    dlat = lat2 - lat1

    a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))

    distance = earth_radius * c  # Unit: km. Parameter does not consider floor number
    print(distance)

    # people share same location (latitude / longitude) but on different floors 
    # --> its ok to put them in same group
    if (distance==0) and (floor_person_1 != floor_person_2): 
      distance = distance + scattering_factor
      print('Identical location but different floors')
      print('lat1:', math.degrees(lat1), 'lon1:', math.degrees(lon1))
      print('lat2', math.degrees(lat2), 'lon2:', math.degrees(lon2)) 

    else: # people share different locations (latitude / longitude)
      pass

    return distance    

这是我将人员分组的功能:

def group_people(all_persons, max_distance_parameter):

    assert len(all_persons) % 9 == 0
    all_persons.set_index("id", drop=False, inplace=True)

    all_persons["host"] = np.nan
    all_persons["group"] = np.nan

    Streufaktor = 0.0001 
    max_distance = max_distance_parameter
    group_number = 0
    group = []
    for index, candidate in all_persons.iterrows():
        if len(group) == 3:
            for person in group:
                all_persons.at[person["id"], "group"] = group_number
            group_number += 1
            group = []

        if len(group) == 0:
            group.append(candidate)
        else:
            for person in group:
                distance = calculate_distance(
                    candidate["latitude"],
                    candidate["longitude"],
                    person["latitude"],
                    person["longitude"],
                    candidate['floor'],
                    person['floor']
                )
                distance = distance 

                if 0 < distance <= max_distance:
                    group.append(candidate)
                    break

接下来,我将函数应用于数据框并查看结果:

group_people(all_persons,4)

all_persons

这就是我得到的:

enter image description here

以黄色显示出问题所在(请参见上面的问题定义)。

我该如何解决? (请检查链接的Google Colab)

0 个答案:

没有答案