Search code examples
pythonpandascsvpandas-loc

Find descriptor in csv file then give it a value


Very new here, as in started yesterday with everything. I am working on a way to pull out one of four categories of weather from this csv file. VFR, MVFR, IFR, LIFR are the categories which every row in the csv should have.

import pandas as pd

ap1 = input('Airport 1: ')
ap2 = input('Airport 2: ')
cat = pd.read_csv('https://www.aviationweather.gov/adds/dataserver_current/current/metars.cache.csv', skiprows=5,
                    index_col='station_id', usecols=['station_id', 'flight_category'])


ap1_cat = cat.loc[ap1]
ap2_cat = cat.loc[ap2]

if ap1_cat == 'VFR':
    print('Green')
elif:
    ap1_cat == 'MVFR':
    print('Blue')
else:
    print('Fail') 

I basically want to say, if flight_category is VFR Print 'Green' etc Any help is appreciated


Solution

  • Your real issue is incorrect use of loc you have not specified that you want to select flight_category column so you are getting a structure that is both the station_id and the flight_category. Personally I add the categorisation to the Dataframe then get it with loc

    cat = pd.read_csv('https://www.aviationweather.gov/adds/dataserver_current/current/metars.cache.csv', skiprows=5,
                        index_col='station_id', usecols=['station_id', 'flight_category'])
    df = cat.reset_index().merge(pd.DataFrame([{"flight_category":"VFR","Color":"Green"},
                            {"flight_category":"MVFR","Color":"Blue"}]),
             on="flight_category").fillna("Fail").set_index("station_id")
    ap1 = "PKWA"
    ap2 = "MMTO"
    print(f"{ap1}: {df.loc[ap1,'Color']} {ap2}: {df.loc[ap2,'Color']}")
    
    

    output

    PKWA: Green MMTO: Blue