0

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?

3
  • Can you show a sample of your dataframe? Do you have a multiindex for rows? Or, do you have the default range index and three columns? Commented Dec 3, 2021 at 2:49
  • I'm currently on my phone so I can't show a sample right now, but I have default range index and three columns. Commented Dec 3, 2021 at 3:05
  • df.query('country == @country')['city'].to_list() No need for loops. Try this after your input line. Commented Dec 3, 2021 at 3:07

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.