简体   繁体   中英

Iterating through a list to then return a value if meeting conditions

I just started working with Pandas for a personal side project of mine. I've imported data from a CSV, cleaned it up and now want to use data from the CSV in the rest of my code. I want to ask a user for input and if the user input matches an entry inside the list (Which is a column inside the data) I want to get data for that instance (from the same row but other columns in the df)

I can get it to compare using the "in" statement but don't think that will work when I expand the functionality.

How would I go about looping through the list from the df to return a value from that list if it exists and then be able to return other values in the same row of the df?

import pandas as pd
import re
import math

housing_Data = pd.read_csv("/Users/saads/Downloads/DP_LIVE_26072020053911478.csv") #File to get data
housing_Data = housing_Data.drop(['INDICATOR', 'MEASURE', 'FREQUENCY', 'Flag Codes'], axis=1) #Removing unwanted Columns
print(housing_Data.columns) # Just to test if working
user_Country = str(input("What Country are you in")) # User Input

def getCountry(): # Function to compare user input to elements inside the list
    if user_Country in housing_Data.LOCATION.unique():
        print(user_Country)
    else:
        print("Sorry we don't have information about that country")


getCountry()

maybe what you want is all rows matching a location?

matching_rows = housing_Data[housing_Data.LOCATION == user_country]
print(matching_rows)

maybe? Im not entirely sure.

In case you are urgent, you can append the iteration list from the source to a newfile.txt and do a comfortable iteration. hopefully it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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