这正常工作:
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
我试图修改上面的代码。在这里,我需要将列m
的值添加到列c
的值并将结果分配给列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
给我错误:
---------------------------------------------------------------------------
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'
问题:如何更正我的第二个代码?如果可能,请提供答案标准函数语法(不是lambda函数)
答案 0 :(得分:3)
添加要在数据帧的axis = 1中考虑的轴并访问函数中的每一列。
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)
或者您可以申请df,而无需选择“ m”和“ c”列。
df["y"] = df.apply(fnc,axis=1)
输出
答案 1 :(得分:1)
尝试此操作,将axis to 1
设置为列级操作,将*x
设置为解包参数。
df["y"] = df[['m','c']].apply(lambda x : fnc(*x), axis=1)