Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
rambutan Avatar asked Oct 24 '25 05:10

rambutan


2 Answers

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("############")



like image 174
rambutan Avatar answered Oct 26 '25 20:10

rambutan


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
like image 37
ALollz Avatar answered Oct 26 '25 18:10

ALollz