Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select by index and by boolean indexing

Input program:

import pandas as pd

df = pd.DataFrame({"A" : ["A0","A1","A2","A3"],
                   "B" : ["dog","cat","dog","dog"]})

myindexes = pd.Index([1,2])

    A    B
0  A0  dog
1  A1  cat
2  A2  dog
3  A3  dog

I want to modify df to get the following output datframe:

       A    B
0     A0  dog
1     A1  cat
2  match  dog
3     A3  dog

I’m trying to do selection by index values (using the variable myindexes) and selection by boolean indexer (must be dog in the column B).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Pandas doesn’t tolerate the following line…But that’s the idea I’m trying to express:

df.loc[(myindexes) & (df["B"] == "dog"), "A"] = "match"

>Solution :

Instead of (myindexes), use df.index.isin(myindexes):

df.loc[df.index.isin(myindexes) & (df["B"] == "dog"), "A"] = "match"

Output:

>>> df
       A    B
0     A0  dog
1     A1  cat
2  match  dog
3     A3  dog
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading