1

I have code here where I'm searching through a series on a pandas dataframe.

                    df[(df['SlyWeekofFiscalYear']==wk) &
                       (df['IB']==bnd) &
                       (df['slyfiscalyear']==yr)]
                    ['Wholesale'].sum()

It's in a function that passes a kwarg bnd=None. Is there a way to disregard the 2nd line of code if bnd=None?

Currently I have a long if statement but I'd like to tidy up the code if possible.

3 Answers 3

2

You can change the second line to ((bnd is None) | (df['IB'] == bnd)). If bnd is None, this produces an all true Series, and since you have & operators, it will have no effect on the result.

Sign up to request clarification or add additional context in comments.

5 Comments

Will the second boolean vector be evaluated if the first condition is true?
@IanS Normally, unlike or or and. | and & have no short circuits. But can't find the docs at this moment.
That's what I suspected. Your word is enough for me :)
So my solution could be marginally faster!
@IanS Hmm, I am suspicious how faster it could be though. | is vectorized and usually pretty fast.
1

Have you tried replacing the second line with some thing that's always true if bnd=None?

Somelike:

((df['IB']==bnd) | (bnd is None))

1 Comment

Perfect - I used your suggestion. So simple but yet it escaped me!
1

You could try a ternary statement:

(df['IB'] == bnd if bnd is not None else True)

The scalar value True should be broadcast properly to a vector of the right length.

Comments

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.