0

Lets say I have a csv as such:

make,model,UCity,UHighway,year
Alfa Romeo,Spider Veloce 2000,23.3333,35,1985
Ferrari,Testarossa,11,19,1985
Dodge,Charger,29,47,1985
Dodge,B150/B250 Wagon 2WD,12.2222,16.6667,1985

I want to access the 'Ucity' and 'Uhighway' columns of specific rows based on user input. So lets say the user inputs 'dodge' as the make and 'charger' as the model and '1985' as the year. Using the users input how would I then access '29' and '47' which is the respective 'Ucity' and 'Uhighway' if possible. I appreciate any and all feedback thank you!

RJ Adriaansen
  • 9,131
  • 2
  • 12
  • 26
o_gulsan
  • 9
  • 2
  • 1
    If the criteria is the same (make->model->data) then you should use a mapping (dicitonary) and the csv module to build the mapping. Once you have a mapping its as simple as `data = mapping.get(make, {}).get(model, {})`. – Reut Sharabani Jul 19 '21 at 18:57

1 Answers1

0

you can use pandas to read in the csv, and go from there https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html

The code should be something along the lines of the following. Please forgive me for not having much time to do thorough testing to see if the code works, but you can refer to the documentation above possibly to see how you can subset and extract data from dataframes

import pandas as pd
df = pd.read_csv('/path/to/file.csv')
make = input('enter the make:')
model = input('enter the model:')

subset = df[(df['make'] == make) & (df['model'] == model)]

The above code subsets the dataframe to the row with the desired data we can now call the specific columns as follows

# We know that there will only be one row
ucity = subset.UCity.values[0]
uhwy = subset.UHighway.values[0]

Now i have the desired values stored in variables and i can do whatever i need with them, like, maybe store them in a dictionary/json? depending on what you need to do with the output

{
    "UCity"   : ucity,
    "UHighway": uhwy
}