pandas Boolean indexing of dataframes Accessing a DataFrame with a boolean index

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

This will be our example data frame:

df = pd.DataFrame({"color": ['red', 'blue', 'red', 'blue']},
                  index=[True, False, True, False])
      color
True    red
False  blue
True    red
False  blue

Accessing with .loc

df.loc[True]
     color
True   red
True   red

Accessing with .iloc

df.iloc[True]
>> TypeError

df.iloc[1]
color    blue
dtype: object

Important to note is that older pandas versions did not distinguish between boolean and integer input, thus .iloc[True] would return the same as .iloc[1]

Accessing with .ix

df.ix[True]
     color
True   red
True   red

df.ix[1]
color    blue
dtype: object

As you can see, .ix has two behaviors. This is very bad practice in code and thus it should be avoided. Please use .iloc or .loc to be more explicit.



Got any pandas Question?