【问题标题】:Using the apply function to pandas dataframe with arguments将 apply 函数用于带有参数的 pandas 数据框
【发布时间】:2020-05-19 06:25:34
【问题描述】:

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

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

在我的 pandas 数据框中我感兴趣的列中使用我的函数:

df["mycol"].apply(myfunc)

不知道为什么会出现这个错误:TypeError:myfunc() missing 1 required positional argument: 'col'

甚至添加axis 表示它应该对待它column wise。我相信我已经通过了我的论点为什么我还需要再次指定col?如果我错了,请纠正我?

非常感谢您的意见

【问题讨论】:

    标签: python python-3.x pandas dataframe apply


    【解决方案1】:

    如果使用Series.apply,那么Series的每个值都是单独处理的,所以需要:

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

    如果想使用 pandas 字符串函数:

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

    如果想传递给函数:

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

    然后使用Series.pipe处理系列:

    df["mycol"].pipe(myfunc)
    

    或者:

    myfunc(df["mycol"])
    

    【讨论】:

    • 太棒了!感谢您的见解。傻我。
    猜你喜欢
    • 2017-09-14
    • 1970-01-01
    • 2012-08-24
    • 2020-04-30
    • 2016-03-20
    • 1970-01-01
    • 2014-03-15
    相关资源
    最近更新 更多