[英]Using the apply function to pandas dataframe with arguments
I created a function to take a column of a string datatype
and ensure the first item in the string is always capitalized
.我创建了一个 function 来获取
string datatype
的列,并确保字符串中的第一项始终capitalized
。 Here is my function:这是我的 function:
def myfunc(df, col):
transformed_df = df[col][0].capitalize() + df[col][1:]
return transformed_df
Using my function in my column of interest in my pandas dataframe:在我的 pandas dataframe 感兴趣的专栏中使用我的 function:
df["mycol"].apply(myfunc)
I don't know why I get this error: TypeError:
myfunc() missing 1 required positional argument: 'col'
我不知道为什么会出现此错误:
TypeError:
myfunc() missing 1 required positional argument: 'col'
Even adding axis
to indicate that it should treat it column wise
.甚至添加
axis
以指示它应该按column wise
处理。 I believe I am already passing my arguments why do I still need to specify col
again?我相信我已经通过了我的 arguments 为什么我还需要再次指定
col
? Correct me if I am wrong?如果我错了,请纠正我?
Your input is highly appreciated非常感谢您的意见
If use Series.apply
then each value of Series is processing separately, so need:如果使用
Series.apply
那么 Series 的每个值都是单独处理的,所以需要:
def myfunc(val):
return val[0].capitalize() + val[1:]
If want use pandas strings functions:如果想使用 pandas 字符串函数:
df["mycol"].str[0].str.capitalize() + df["mycol"].str[1:]
If want pass to function:如果要传递给 function:
def myfunc(col):
return col.str[0].str.capitalize() + col.str[1:]
Then use Series.pipe
for processing Series:然后使用
Series.pipe
进行加工系列:
df["mycol"].pipe(myfunc)
Or:或者:
myfunc(df["mycol"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.