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
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)