When should I (not) want to use pandas apply() in my code?

后端 未结 4 826
悲哀的现实
悲哀的现实 2020-11-21 05:19

I have seen many answers posted to questions on Stack Overflow involving the use of the Pandas method apply. I have also seen users commenting under them saying

4条回答
  •  萌比男神i
    2020-11-21 05:47

    For axis=1 (i.e. row-wise functions) then you can just use the following function in lieu of apply. I wonder why this isn't the pandas behavior. (Untested with compound indexes, but it does appear to be much faster than apply)

    def faster_df_apply(df, func):
        cols = list(df.columns)
        data, index = [], []
        for row in df.itertuples(index=True):
            row_dict = {f:v for f,v in zip(cols, row[1:])}
            data.append(func(row_dict))
            index.append(row[0])
        return pd.Series(data, index=index)
    

提交回复
热议问题