vendredi 7 mai 2021

How to create function that will give distance from the data frame if the input city matches the city in the data frame?

I have a data frame in pandas that looks like this extracted from a CSV file:

                 CITY  DISTANCE
0           Albany NY      1814
1          Atlanta GA      1415
2         Billings MT       555
3            Boise ID       830

I attempted to create a function using a for-loop. if the input string matches the string in the 'CITY' column print the distance.

import pandas as PD

def fetch_distance(name):
    df = pd.read_csv("cities_list.csv")
    for i in df:
        if i in df[df['CITY'].str.match('CITY').shift(2).fillna(False)]:
            return i
    else:
        pass
print(fetch_distance("Atlanta GA"))

It returns the name of the column instead. I am still a beginner in coding thank you for your help.

OUTPUT:

CITY

Aucun commentaire:

Enregistrer un commentaire