pandas.DataFrame.Loc

Asked

Viewed 158 times

0

I have the following situation:

d= {'files': ['f1.txt', 'f2.txt', 'f3.txt'], 'url': ['url1', 'url2', 'url3'], 'nav': [False, True, False]}
df = pd.DataFrame(d)
    files   url    nav
0  f1.txt  url1  False
1  f2.txt  url2   True
2  f3.txt  url3  False

So in possession of the Dataframe, I can search two fields in a certain condition:

df.loc[~df.nav][['files', 'url']]
    files   url
0  f1.txt  url1
2  f3.txt  url3

Or just a field with a certain condition:

df.loc[~df.nav]['files']
0    f1.txt
2    f3.txt

Here comes the problem. I want to iterate on a loop for + enumerate

With only 1 field works:

for i, file in enumerate(df.loc[~df.nav]['files']):
     print(i, file)

0 f1.txt
1 f3.txt

With 2 fields:

for i, file in enumerate(df.loc[~df.nav][['files', 'url']]):
    print(i, file)
0 files
1 url

With 2 fields, this way presents error:

for i, file in enumerate(df.loc[~df.nav]['files', 'url']):
    print(i, file)

How can I resolve this situation?

  • "I want to iterate in a loop for + enumerate". Why not use .iterrows() to iterate the dataframe? for index, row in df.loc[~df.nav].iterrows():, print(index, row['files'], row['url']).

  • @Alexciuffa, your solution is perfect for me. I have now met this possibility. Thank you very much.

  • Why don’t you put this tip as answer to the question?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.