Home > Blockchain >  Python loop over all the rows of a dataframe
Python loop over all the rows of a dataframe

Time:08-04

I'm trying to write a loop to return df.iloc[0], df.iloc[1], df.iloc[2] ... df.iloc[the last row] so that every row can be fed to another function. Thanks!

CodePudding user response:

Something like this?

import pandas as pd

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
for ind in df.index:
    print(df.iloc[ind])

CodePudding user response:

You could use a dataframe.apply() approach and set the axis value = 1:

import pandas as pd

Test = pd.DataFrame(
    {
     "Col1":[1, 2, 3, 4],
     "Col2":[11, 12, 13, 14]
     }
    )

Test["Row_multiply"] = Test.apply(
    lambda row: row["Col1"]*row["Col2"], axis=1
    )

Result:

   Col1  Col2  Row_multiply
0     1    11            11
1     2    12            24
2     3    13            39
3     4    14            56

I just gave the example of a simple multiplication between row values, but you can get fairly complex. If you provide an example (minimally reproducible example) I can use whatever function you need.

  • Related