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.
CodePudding user response:
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.
CodePudding user response:
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