2

This works correctly:

import pandas as pd

def fnc(m):
    return m+4

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
df
# apply a self created function to a single column in pandas
df["y"] = df['m'].apply(fnc)
df

I tried to modified code above. Here I need to add column m value to column c value and assign result to column y:

import pandas as pd

def fnc(m,c):
    return m+c

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
df
# apply a self created function to a single column in pandas
df["y"] = df[['m','c']].apply(fnc)
df

gives me error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
d:\del\asfasf.py in 
      8 df
      9 # apply a self created function to a single column in pandas
----> 10 df["y"] = df[['m','c']].apply(fnc)
     11 df

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, raw, result_type, args, **kwds)
   6876             kwds=kwds,
   6877         )
-> 6878         return op.get_result()
   6879 
   6880     def applymap(self, func) -> "DataFrame":

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self)
    184             return self.apply_raw()
    185 
--> 186         return self.apply_standard()
    187 
    188     def apply_empty_result(self):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self)
    294             try:
    295                 result = libreduction.compute_reduction(
--> 296                     values, self.f, axis=self.axis, dummy=dummy, labels=labels
    297                 )
    298             except ValueError as err:

pandas\_libs\reduction.pyx in pandas._libs.reduction.compute_reduction()

pandas\_libs\reduction.pyx in pandas._libs.reduction.Reducer.get_result()

TypeError: fnc() missing 1 required positional argument: 'c'

Question: How to correct my second code? If possible, please provide answer standard function syntax (not lambda function)

vasili111
  • 6,032
  • 10
  • 50
  • 80

2 Answers2

4

Add axis to consider in axis=1 in dataframe and access each column inside the function.Try this

def fnc(m):
    return (m.m+m.c)

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
df["y"] = df[['m',"c"]].apply(fnc,axis=1)

or you can apply to df,without select "m" and "c" columns.

df["y"] = df.apply(fnc,axis=1)

output

Rajith Thennakoon
  • 3,975
  • 2
  • 14
  • 24
2

try this, set axis to 1 for column wise operation & *x for un-packing arguments.

df["y"] = df[['m','c']].apply(lambda x : fnc(*x), axis=1)
sushanth
  • 8,275
  • 3
  • 17
  • 28