使用带参数的pandas数据框的apply函数

问题描述 投票:0回答:1

我创建了一个函数来获取string datatype的列,并确保字符串中的第一项始终为capitalized。这是我的功能:

def myfunc(df, col):
     transformed_df = df[col][0].capitalize() + df[col][1:]
     return transformed_df

在我的熊猫数据框中感兴趣的列中使用我的功能:

df["mycol"].apply(myfunc)

我不知道为什么会收到此错误:TypeError: myfunc() missing 1 required positional argument: 'col'

甚至添加axis表示应该对其进行处理column wise。我相信我已经在通过辩论了,为什么还需要再次指定col?如果我错了,请纠正我吗?

非常感谢您的投入

python python-3.x pandas dataframe apply
1个回答
1
投票

因为起作用是传递Series的值:

def myfunc(val):
     return val[0].capitalize() + val[1:]

如果要使用熊猫字符串功能:

df["mycol"].str[0].str.capitalize() + df["mycol"].str[1:]

如果可能要传递给功能,请使用Series.pipe

Series.pipe

或:

def myfunc(col):
    return col.str[0].str.capitalize() + col.str[1:]

df["mycol"].pipe(myfunc)
© www.soinside.com 2019 - 2024. All rights reserved.