pythonpandasdataframeobject-slicing

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).

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