Home > front end >  How to access dataframe rows based on user input
How to access dataframe rows based on user input

Time:12-04

How can I access dataframe rows based on user input? Let's say I have a csv file with countries in the world. The first column would be "continent", the second would be "country" and the third would be "city".

How can I get all the values from "city" if I choose a certain country?

df = pd.read_csv("file.csv")


if continent == 'europe':
country = input("Choose a country:")
for index, row in enumerate(df.index):
    city = df.values[index]
    print(city)

With this code I'm just printing out every city in every country. I want to only get German cities if I type Germany. Where do I place the "country" variable in the for loop?

CodePudding user response:

You don't need a for loop for this. Assuming your dataframe columns are called "continent", "country", and "city", something like this should work:

input_country= input("Choose a country:")
print (df.loc[df.country==input_country].city)
  • Related