S. 16 S. 16 - 1 year ago 91
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

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("Not Found")

Answer Source

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":
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download