I have a DataFrame
| index | Street | House | Building |
|---|---|---|---|
| 1 | ABC | 20 | a |
| 2 | ABC | 20 | b |
| 3 | ABC | 21 | NaN |
| 4 | BCD | 2 | 1 |
Need to create a multiple selection from this DataFrame:
- If Street == str_filter;
- If House == house_filter;
- If Building == build_filter AND If Building is not NULL;
I've already tried df[(df['Street'] == str_filter) & (df['House'] == house_filter) & ((df['Building'] == build_filter) & (pd.notnull(df['Building'])))
But doesn't lead to a result I particularly want to see. I have to check if the Building value is not NaN and if it's true select the row with the certain Building num. However, I also want to select the row if it has NaN value for the Building but also meets other criteria.
Another idea was to create lists for the set of filter values and the set of this values meeting pd.notnull criteria:
filter_values = [str_filter, house_filter, build_filter]
notnull_values = [pd.notnull(entry) for entry in filter_values]
This one doesn't meet the performance criteria, because I have extremely huge DataFrame and creating additional lists with additional filtering will lead to the out-performance. Possible solution may lay in the df.loc function, but I don't know how to realise it.
To summarise, the problem is the following: How to create multiple selection in pandas with conditions for NaN values?
UPD: It seems that the function I have to use is df[... & (df['Building'] == 'a' if pd.notnull(df['Building']))] using an analogy with lambda apply trick