Home > database >  Apply peicewise function for each element in a DataFrame
Apply peicewise function for each element in a DataFrame

Time:03-26

I have a Pandas DataFrame of the type:

1 2 3 4
1 2 5 6
...

I have a list of functions of the same length as one of the rows, for example,

a = lambda x: x**2
b = lambda x: x**3
c = lambda x: x
d = lambda x: x 1
funcs = [a,b,c,d]

If applied to the DataFrame above it should output

1 8 3 5
1 8 5 7
...

Is there a simple way to do this?

CodePudding user response:

Use DataFrame.agg with dictionary by columns names and functions:

df = df.agg(dict(zip(df.columns, funcs)))
print (df)
   0  1  2  3
0  1  8  3  5
1  1  8  5  7

Details:

print (dict(zip(df.columns, funcs)))
{0: <function <lambda> at 0x000000000DD10310>,
 1: <function <lambda> at 0x0000000010D58040>, 
 2: <function <lambda> at 0x0000000010D580D0>, 
 3: <function <lambda> at 0x0000000010D58160>}
  • Related