Home > Software design >  How can I apply a function to many columns in a dataframe using a single column as an argument?
How can I apply a function to many columns in a dataframe using a single column as an argument?

Time:10-28

I have a dataframe with 100 columns I need to apply a function to, but I can't figure out how to pass the first column as an argument.

For example, if my table is:

df = pd.DataFrame({'argument':[1,2,0.5],
                   'day1':[4,5,6],
                   'day2':[5,1,2]})

   argument day1 day2 day3...
0  1.0      4    5
1  2.0      5    1
2  0.5      6    2

And I have a function like this (mine is much more complicated, this is just for the example):

def function (i,j):
    return i * j

I would like my output to be:

   argument day1 day2 day3...
0  1.0      4    5
1  2.0      10   2
2  0.5      3    1

This is getting me very strange results, does anyone know what I'm doing wrong? Thank you!

def function (i,j):
    return i- j
df = df.apply(function, axis=1, j=df['argument'])

CodePudding user response:

First, you have the wrong direction for your axis, it should be set to be 0 instead of 1.

Second, if you apply your function like that, it will apply the function to your argument column. And it won't be the same as what you wanted there.

So, change your code become like this

import pandas as pd

def function (i,j):
    return i * j

df = pd.DataFrame({'argument':[1,2,0.5],
                   'day1':[4,5,6],
                   'day2':[5,1,2]})

df2 = df.iloc[:,-2:].apply(function,axis=0,j=df['argument'])
df.iloc[:,-2:] = df2
print(df)
  • Related