1

I am trying to browse my DF doing :

for row in range(len(DF)):
    for col in range(len(DF.columns)):
        print(DF[row][col])

but doing so throw :

KeyError: 0

I am wondering, how to browse a whole dataframe (including col name and excluding index) using only col number and row number.

2 Answers 2

1

If need select values by indices use DataFrame.iat/ DataFrame.iloc:

for row in range(len(DF)):
    for col in range(len(DF.columns)):
        print(DF.iat[row, col])
        #print(DF.iloc[row, col])

Better selecting by values of index, columns, it is same ouput if not duplicated index/columns values use DataFrame.at/DataFrame.loc:

for row in DF.index:
    for col in DF.columns:
        print(DF.at[row, col])
        #print(DF.loc[row, col])

BUT if possible use some vectorized solution the best is avoid looping.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, why should I avoid using range and len ?
@TourEiffel - if no duplicates in index/ columns yes.
How do I display column name before the first line of the DF ?
0

A nice option might be to stack and use a single loop:

for (row, col), value in df.stack().items():
    print(row, col, value)

Example:

i A 0
i B 1
i C 2
j A 3
j B 4
j C 5
k A 6
k B 7
k C 8

used input:

   A  B  C
i  0  1  2
j  3  4  5
k  6  7  8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.