python3中的For循环(多次迭代)

2024-09-30 00:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我读了一个名为df的csv文件,它有4列(id,skill,…)和30行,我希望程序检查每个id,如果id是“A035755”,那么打印它的相关skill(j)。我写了下面的程序,它几乎可以工作,但问题是,它反复多次,所以不是30个结果,我有超过100!
我想我的索引可能是问题,但不知道如何解决它。你知道吗

谢谢,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")

Tags: 文件csvin程序iddfforread
2条回答

如果我理解正确,df的属性(测向id, 测向技能)表示列表中的列和索引(测向id[1..n])表示行,则正确的方法如下:

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])

因此可以迭代和引用索引。像这样

for index,value in df.id.items():  #id is one of the columns
        if value == "A035755":
            print(df.skill[index])
        else:
            print("Not Found")

或者你可以迭代records

for record in df:
    if record.id == "A035755":
        print(record.skill)
    else:
        print("Not Found")

相关问题 更多 >

    热门问题