jeudi 22 août 2019

python2.7: How to compare timestamps from two tables and assign values to one of them, based on comparison

I'm new to coding and to python, and I need your help to solve one issue. I have 2 tables: One called "stops", with several columns, including: Stopid and stop_time. Another one called "path", with several other columns, including Timestamp and tripid. I need to compare Timestamp in the path table and stop_time in the stops table, and assign a value to tripid Depending on such comparison.

If the Timestamp of an instance i of path is within the stop_time of two consecutive instances (j, j+1) of stops, then the tripid for such instance i of path must be equal to the stopid of instance j of stops.

The stops table is this:

stops

The path table (partial) looks like this:

Path

I tried the code shown below, which runs, but doesn't produce the desired results.

    for j in range(len(trips.stops)-1):
        for i in range(len(trips.path)-1):
            if trips.path['Timestamp'][i] > trips.stops['stop_time'][j] and trips.path['Timestamp'][i] <= trips.stops['stop_time'][j+1]:
                trips.path['tripid'] = trips.stops['stopid']

The results I get (shown below) assign numbers to only a portion of all the elements of the path table, and they are incorrect. By (manually) observing and comparing the times in two tables, I know the correct values are the ones shown in the column tripid_expected:

tripid results and expected

Aucun commentaire:

Enregistrer un commentaire