Home > Back-end >  how to compare two uneven dataset columns with each other?
how to compare two uneven dataset columns with each other?

Time:06-01

enter image description here

As shown in the above picture there are two datasets that do not have the same row count. The task is to compare the distance between each city to the range each vehicle can travel i.e. (compare the distance between city1 & city2 with all the vehicle type ranges.)

CodePudding user response:

Let's assume that we have 2 dictionaries(If you have a DataFrame, you can use to_dict() method to convert it to the dictionary)

vehicles = {'A320': 5000, 'A330': 8000, 'B737': 5000, 'B747': 10000, 'Q400': 1500, 'ATR72': 1000}
city_distances = {'AA-BB': 3000, 'BB-CC': 6500, 'CC-AA': 400, 'AA-DD': 1000}

You can simply create a nested for loop and check whatever condition you want. I, for example, did check, whether the vehicle could travel the city route.

for city_route in city_distances.keys():
    for vehicle in vehicles.keys():
        if vehicles[vehicle] >= city_distances[city_route]:
            print(f'Vehile {vehicle} can travel the {city_route} route')
        else:
            print(f"Vehile {vehicle} can't travel the {city_route} route")

CodePudding user response:

Well, you didn't tell/show us the expected output, so I'll give you the code to let you .merge() both DF, from there you can do pretty everything you want:

df3 = df2.merge(df1, how='cross')
df3

Truncated result:

index city_a city_b vehicles range
0 AA-BB 3000 A320 5000
1 AA-BB 3000 A330 8000
2 AA-BB 3000 B737 5000
3 AA-BB 3000 B747 10000
4 AA-BB 3000 Q400 1500
5 AA-BB 3000 ATR72 1000
6 BB-CC 6500 A320 5000
7 BB-CC 6500 A330 8000

...

index city_a city_b vehicles range
16 CC-AA 400 Q400 1500
17 CC-AA 400 ATR72 1000
18 AA-DD 1000 A320 5000
19 AA-DD 1000 A330 8000
20 AA-DD 1000 B737 5000
21 AA-DD 1000 B747 10000
22 AA-DD 1000 Q400 1500
23 AA-DD 1000 ATR72 1000

Please accept ✅ this answer if it solved your problem, it motivates me :)

Otherwise mention me (using @) in comment while telling me what's wrong ;)

  • Related