vks vks - 1 month ago 12
Python Question

Pandas Get a list of index from dataframe.loc

I have looked through various sites and SO posts.Seems easy but somehow i am stuck with this.I am using

print frame.loc[(frame['RR'].str.contains("^[^123]", na=False)), 'RR'].isin(series1.str.slice(1))


to get

3 True
4 False
8 False
Name: RR, dtype: bool


Now,somehow i want the
indexes
only so that i can use that in
dataframe.drop
. Basically all the indexes where value is
True
, i have to grab
indexes
and
drop
them.Is there any other way as well without using
indexes
?

Answer

You are testing two conditions on the same column so these can be combined (and negated):

frame[~((frame['RR'].str.contains("^[^123]", na=False)) & (frame['RR'].isin(series1.str.slice(1))))]

Here, after ~ operator, it checks whether a particular row satisfies both conditions - same as the boolean array you get in the end. With ~, you turn True's to False's and False's to True's. Finally, frame[condition] returns the rows that satisfy the final condition with boolean indexing.

In a more readable format:

condition1 = frame['RR'].str.contains("^[^123]", na=False)
condition2 = frame['RR'].isin(series1.str.slice(1))
frame[~(condition1 & condition2)]

As an alternative (requires 0.18.0), you can get the indices of the True elements with:

frame.loc[(frame['RR'].str.contains("^[^123]", na=False)), 'RR'].isin(series1.str.slice(1))[lambda df: df].index
Comments