Iterating over whole Pandas DataFrame with one variable

Viewed 46

I thought my request was pretty simple but it seems like there might be no solution the way I would like it to be. Let's say I have the following DataFrame:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])

What I'm looking for is a function that would allow me to iterate over every cell in the DataFrame with the iteration variable being the content of the current cell. Something like

for i in df.function():
    print(i)

Ideally, this print command should count from 1 to 9 in this example. Is there a DataFrame function that would enable something like this?

1 Answers

You can iterate over the flattened underlying numpy array:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
#    0  1  2
# 0  1  2  3
# 1  4  5  6
# 2  7  8  9

for cell in df.to_numpy().ravel():
    print(cell, end=', ')

output:

1, 2, 3, 4, 5, 6, 7, 8, 9, 
iterating through rows first:
for cell in df.to_numpy().ravel(order='F'):
    print(cell, end=', ')

output:

1, 4, 7, 2, 5, 8, 3, 6, 9, 
Related