Search code examples
pythonpython-3.xcsvfilepython-3.9

getting specific data from a csv file, I want the user to input the values of model, speed and brake level, and the output is the distance of that row


this is the code to generate the dataset I used for the searching code below, this block of code also have a problem of leaving an line after every row if that can be fixed too it would be really helpful :

*

**import csv
def generate():
  index =0
  distance =0
  with open('dataset.csv', mode='w') as file:
    writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["model" ,"speed" ,"breaks" , "distance"])
    for model in range(6):
        for speed in range (290):
          for breaks in range (3):
            if model == 2 :
              modelbreak = 15
            if model == 0 :
              modelbreak = 13
            if model == 4 :
              modelbreak = 11
            if model == 1 :
              modelbreak = 10
            if model == 3 :
              modelbreak = 9
            if model == 5 :
              modelbreak = 7
            distance = (3- breaks) *speed / ((modelbreak+1) )
            index = index +1
            writer.writerow([str(model) , str(speed+10) ,  str(breaks) , str("%.2f" %distance)])
generate()**

and this is the code I made to print the 'distance' column, I am new to python and I can't seem to find an option which will allow me to give the code my inputs in this case (model, speed and brake level) to get (distance) :


import csv
import pandas as pd
from _csv import reader
#getting input
x = input('model number:')
z = input('speed:')
q = input('break level:')
x1 = int(x)
z1 = int(z)
q1 = int(q)
target = pd.read_csv('DataSet.csv')
#target = csv.reader(open('DataSet.csv', "r"), delimiter=",")
row = 0
for model in range(6):
    for speed in range(300):
        for breaks in range(3):
            row = row + 1
            if model == x1 and speed == z1 and breaks == q1:
                output = target(distance)
                print(output)


Solution

  • To find distance in a dataframe, you can filter instead of loops, This would work:

    import csv
    import pandas as pd
    from _csv import reader
    #getting input
    x = input('model number:')
    z = input('speed:')
    q = input('break level:')
    x1 = int(x)
    z1 = int(z)
    q1 = int(q)
    target = pd.read_csv('dataset.csv')
    #target = csv.reader(open('DataSet.csv', "r"), delimiter=",")
    distance = target[(target['model']==x1) & (target['speed']==z1) & (target['breaks']==q1)]
    print(distance.iloc[0]['distance'])
    

    Also, you are saving your file with this name: dataset.csv in the dataset creation code.