简体   繁体   English

如果满足条件,遍历一个列表然后返回一个值

[英]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.我刚开始使用 Pandas 进行我的个人项目。 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.我已经从 CSV 导入数据,清理它,现在想在我的代码的 rest 中使用来自 CSV 的数据。 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)我想向用户询问输入,如果用户输入与列表中的条目匹配(这是数据中的一列),我想获取该实例的数据(来自同一行但 df 中的其他列)

I can get it to compare using the "in" statement but don't think that will work when I expand the functionality.我可以使用“in”语句对其进行比较,但认为在我扩展功能时不会起作用。

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?我将如何 go 循环遍历 df 中的列表以从该列表中返回一个值(如果存在),然后能够在 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.万一你急了,你可以append 把迭代列表从源文件改成一个newfile.txt,然后做一个舒服的迭代。 hopefully it helps.希望它有所帮助。

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

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