rambutan
rambutan

Reputation: 389

How to iterate over every cell in pandas Dataframe?

How to iterate over every cell of a pandas Dataframe?

Like

for every_cell in df.iterrows:
   print(cell_value)

printing of course is not the goal. Cell values of the df should be updated in a MongoDB.

Upvotes: 4

Views: 12632

Answers (3)

Barbaros Özhan
Barbaros Özhan

Reputation: 65218

One technique as an option would be using double for loop within square brackets such as

for i in [df[j][k] for k in range(0,len(df)) for j in df.columns]:
    print(i)

in order to iterate starting from the first column to the last one of the first row, and then repeat the same process for each row by the order of members of lists.

Upvotes: 1

ALollz
ALollz

Reputation: 59529

You can use applymap. It will iterate down each column, starting with the left most. But in general you almost never need to iterate over every value of a DataFrame, pandas has much more performant ways to accomplish calculations.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(6).reshape(-1, 2), columns=['A', 'B'])
#   A  B
#0  0  1
#1  2  3
#2  4  5

df.applymap(lambda x: print(x))
0
2
4
1
3
5

If you need it to raster through the DataFrame across rows you can transpose first:

df.T.applymap(lambda x: print(x))
0
1
2
3
4
5

Upvotes: 3

rambutan
rambutan

Reputation: 389

if it has to be a for loop, you can do it like this:

def up_da_ter3(df):
    
    columns = df.columns.tolist()
    
    for _, i in df.iterrows():
        
        for c in columns:
            print(i[c])
            print("############")



Upvotes: 5

Related Questions