0

I am trying to read the dataframe line by line in a loop.

There is a data frame df['col_1', 'col_2', 'col_n'], there is also a certain function f(df) that takes one row of the dataframe as arguments.

Could somebody helps me with the code to read a dataframe line by line in a loop and apply a f() function to each row.

PS: Here, input value to the function f() must me a dataframe, because it processes the data referring to column names.

Thanks!

Stoner
  • 846
  • 1
  • 10
  • 30
Shokan
  • 13
  • 4
  • Possible duplicate of [apply a function to each row of the dataframe](https://stackoverflow.com/questions/50421196/apply-a-function-to-each-row-of-the-dataframe) – roganjosh Sep 21 '19 at 08:03
  • I don't understand "input value to the function f() must me a dataframe, because it precesses the data referring to column names.". Why not just change function? It doesn't make sense to have a function that expects single-row dfs – roganjosh Sep 21 '19 at 08:05
  • See http://jonathansoma.com/lede/foundations/classes/pandas%20columns%20and%20functions/apply-a-function-to-every-row-in-a-pandas-dataframe/ – Stoner Sep 21 '19 at 08:37
  • @Massifox Yeaps, its good. :) – Stoner Sep 23 '19 at 00:52
  • @Massifox Sadly, I am not the one who posted the question.. So I am unable to accept it. :) – Stoner Sep 23 '19 at 01:01
  • Ops ahah sorry, I need to sleep :) – Massifox Sep 23 '19 at 01:05

1 Answers1

1

If I understand your question correctly, this code is for you:

def f(row):
    return str(row['A'] + 1) + str(row['B']).upper()

df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})

df['new_col'] = df.apply(lambda row: f(row),axis=1)
# output
   A  B new_col
0  1  x      2X
1  2  y      3Y
2  3  z      4Z

Or if you want to update the row values:

def f2(row):
    row['A'] = row['A'] + 1
    row['B'] = row['B'].upper()
    row['new_col'] = str(row['A']) + str(row['B'])
    return row
df.apply(f2, axis=1)
#output
   A  B new_col
0  2  X      2X
1  3  Y      3Y
2  4  Z      4Z
Massifox
  • 4,369
  • 11
  • 31