bernando_vialli
bernando_vialli

Reputation: 1019

Using the OR operator seems to only take the first of two conditions when used with np.where filter

Here is a small sampling of my dataset:

Search_Term    Exit_Page                  Unique_Searches    Exit_Pages_actual
nitrile gloves /store/catalog/product.jsp?        10        /store/catalog/product.jsp?
zytek gloves   /store/product/KT781010            20        /store/pro

So this should be pretty easy, not sure why I am not getting it to work. I am trying to pull into the Exit_Pages_actual column when the all the characters in the Exit_Page when the first 10 characters are "/store/pro" or "/store/cat". When that is not the case, I want it to pull in only the first 10 characters from Exit_Page. As you can see above, my code works fine for the catalog but not for the product (aka works for the first condition in my OR but not the 2nd per the code below). What is wrong? So there is no error message, it just does not gives me the right result for product, only outputs the first 10 characters rather then the whole string:

Exit_Pages['Exit_Pages_actual'] = np.where(Exit_Pages['Exit_Page'].str[:10]==('/store/cat' or '/store/pro'),Exit_Pages['Exit_Page'].str[:],Exit_Pages['Exit_Page'].str[:10])

Exit_Pages  

Upvotes: 0

Views: 52

Answers (1)

Dylan
Dylan

Reputation: 427

@tw-uxtli51nus in the comments is basically correct.

We can accomplish what you want by wrapping logical conditions with () and using '|' in place of 'or'.

So np.where would look like:

df['new_col'] = np.where(
    (
    (df['Exit_Page'].str[:10]=='/store/cat')
    |
    (df['Exit_Page'].str[:10]=='/store/pro')
    )
    ,df['Exit_Page']
    ,df['Exit_Page'].str[:10])

trying to make it more readable since this stuff is ugly to look at.

We can make our lives easier by instead trying a technique similar to what the docs suggest using np.isin(): https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html

but I don't have the correct version of numpy to write out a real example, unfortunately.

Upvotes: 1

Related Questions