1

I have a function

def return_true_false(a,b,c):
    '''
    returns true if stuff, else returns false
    '''

I then apply this function to a Dataframe twice to split the dataframe on the result

df_True =  df[df.apply(lambda x: return_true_false(x[a],x[b],x[c]),axis=1)]
df_false =  df[df.apply(lambda x: not return_true_false(x[a],x[b],x[c]),axis=1)]

However, this does the calculation twice on each row. My question is, is there a way to split this dataset on a function and only go through the dataset once?

1 Answer 1

1

IIUC, run it once assigning the result (to mask for example), then using boolean indexing:

mask = df.apply(lambda x: return_true_false(x[a],x[b],x[c]),axis=1)

df_True = df[mask]
df_false = df[~mask]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This seems so obvious in hindsight

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.