简体   繁体   English

接受用户输入并使用Pandas Python在CSV中搜索

[英]Taking user input and searching through a csv using pandas python

I'm trying to take user input and search the csv file by asking the make, model, and year of the car but it is not filtering the cars correctly when I get to model. 我试图通过询问汽车的品牌,型号和年份来接受用户输入并搜索csv文件,但是在我建模时,它并不能正确过滤汽车。 It is still showing all the car models even when I want only Toyota cars. 即使我只想要丰田汽车,它仍然显示所有汽车型号。 I am also getting Empty dataframe error when I finish the input. 完成输入后,我也收到Empty dataframe错误。

sData.csv sData.csv

import pandas

# reads in vehicle Data
df = pandas.read_csv('sData.csv')
pandas.set_option('display.max_columns', None)
pandas.set_option('display.width', 400)

def get_choice(data, column):

    #Gets user choice
    nums = [val for val in range(len(df[column].unique()))]
    choices = list(zip(nums, df[column].unique()))
    print("Select '%s' of the car\n" % column)
    for v in choices:
        print("%s.  %s" % (v))
    user_input = input("Answer: ")
    user_answer = [val[1] for val in choices if val[0]==int(user_input)][0]
    print("'%s' = %s\n" % (column, user_answer))
    return user_answer

def main():

    make_input = get_choice(data=df, column="make")
    model_input = get_choice(data=df, column="model")
    year_input = get_choice(data=df, column="year")
    newdf = df.loc[(df["make"]==make_input)&(df["model"]==model_input)&(df["year"]==year_input)]
    print(newdf)

if __name__ == "__main__":
    main()

The issue you are having with regards to models not being filtered by make is caused by the fact that you are not modifying df or passing a modified copy of it to the subsequent calls to make_choice . 关于不通过make过滤模型的问题是由于您没有修改df或将其修改后的副本传递给make_choice的后续调用make_choice Essentially, each time you call make_choice the results are not filtered by prior choices. 本质上,每次调用make_choice ,结果都不会被先前的选择过滤。

There are multiple possible solutions, one would be to simply update df as you make choices, but this wouldn't keep the original df . 有多种可能的解决方案,一种是在做出选择时简单地更新df ,但这不会保留原始df

make_input = get_choice(data=df, column="make")
df = df.loc[df.make == make_input, :]
...

Alternatively: 或者:

filtered_df = df.copy() # Could be costly if df is large
make_input = get_choice(data=filtered_df, column="make")
filtered_df = filtered_df.loc[filtered_df.make == make_input, :]
model_input = get_choice(data=filtered_df, column="model")
...

As for the empty data frame error, I would advise to use a debugger and see what each step of your code is yielding. 至于空数据帧错误,我建议您使用调试器,看看代码的每一步产生了什么。 If you do not already know how to use it, I would recommend you to look at pdb . 如果您还不知道如何使用它,建议您看一下pdb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM