vas*_*111 2 python functional-programming function python-3.x pandas
这可以正确工作:
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
Run Code Online (Sandbox Code Playgroud)
我尝试修改上面的代码。这里我需要将列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
Run Code Online (Sandbox Code Playgroud)
给我错误:
---------------------------------------------------------------------------
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'
Run Code Online (Sandbox Code Playgroud)
问题:如何更正我的第二个代码?如果可能,请提供答案标准函数语法(不是 lambda 函数)
添加要在数据帧中的 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)
Run Code Online (Sandbox Code Playgroud)
或者您可以应用于 df,而不选择“m”和“c”列。
df["y"] = df.apply(fnc,axis=1)
Run Code Online (Sandbox Code Playgroud)
输出
归档时间: |
|
查看次数: |
3376 次 |
最近记录: |