2

I need to grab values where the column startswith either value 'MA', 'KP'.

I am trying to chain my dataframe query as such:

df.loc[df['REFERRAL_GRP'].str.startswith("KP")==True | df['REFERRAL_GRP'].str.startswith("MA")==True]

This doesn't seem to work because the column contains pd.nan objects (NULL values).

By themselves, the queries work, how can I merge these two queries together?

Thank you

Here is my error message:

Traceback (most recent call last): Debug Probe, prompt 40, line 1 File "c:\Python27\Lib\site-packages\pandas\core\generic.py", line 892, in __nonzero__ .format(self.__class__.__name__)) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

2
  • So, the column name needs to start with either "MA" or "KP?" Then why are you trying to grab the values starting with "MA" or "KP"? Your question and attempt are at odds with each other. Commented Jan 3, 2017 at 17:35
  • is that expression being used in an if, for or some other conditional? Commented Jan 3, 2017 at 17:45

2 Answers 2

2

This is a question we see a lot.

df.loc[
    # 2. This returns a whole lot of `True`s or `False`s
    df['REFERRAL_GRP'].str.startswith("KP")==True
    # 1. `|` is expecting a `True` or `False`
    | 
    # 2. This returns a whole lot of `True`s or `False`s
    df['REFERRAL_GRP'].str.startswith("MA")==True
]

Fix it by wrapping conditions with parenthesis

df.loc[
    # 1. Series of `True`s or `False`s
    (df['REFERRAL_GRP'].str.startswith("KP")==True)
    # 2. `|` is now a operator on `pd.Series` and is expecting `pd.Series`
    | 
    # 1. Series of `True`s or `False`s
    (df['REFERRAL_GRP'].str.startswith("MA")==True)
]

That said, I'd do this

df.loc[df.REFERRAL_GRP.str.match('^KP|MA')]
Sign up to request clarification or add additional context in comments.

Comments

2

try numpy logical_or

import numpy as np
df.loc[np.logical_or(df['REFERRAL_GRP'].str.startswith("KP")==True , df['REFERRAL_GRP'].str.startswith("MA")==True)]

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.