RichWolff
RichWolff

Reputation: 45

Python Pandas Data Frame search

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.

Upvotes: 1

Views: 92

Answers (3)

Jan Zeiseweis
Jan Zeiseweis

Reputation: 3738

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

Somelike:

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

Upvotes: 1

akuiper
akuiper

Reputation: 214957

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.

Upvotes: 2

IanS
IanS

Reputation: 16241

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.

Upvotes: 1

Related Questions