S. 16 S. 16 - 11 days ago 6
Python Question

For loop in python 3 (multiple Iteration)

I read a csv file named df, which has 4 columns(id, skill,..) and 30 rows, I want the program to check each id and if the id is "A035755" then print its related skill (j). I wrote the following program it almost works but the problem is it iterates more than once so instead of 30 results I have more than 100!

I think my indexing might be the problem but not sure how to fix it.

Thanks J

df=pd.read_csv('location')
for i in df.id[0:len(df)]: #id is one of the columns
for j in df.skill: #skill another column
if i == "A035755":
print(j)
else:
print("Not Found")

Answer

If I understand correctly, df's attributes (df.id, df.skill) represent columns and indexes in the lists (df.id[1..n]) represent rows, then proper way is following:

df = pd.read_csv('location')
for index, rec_id in enumerate(df.id):  #id is one of the columns
    if rec_id == "A035755":
        print(df.skill[index])
Comments