How to select the inverse index in pd.DataFrame by using loc
or iloc
?
I tried df.loc[!my_index,my_feature]
but fail.
You may take advantage of index.difference
.
idx2 = df.index.difference(my_index)
Or, set.difference
idx2 = set(df.index).difference(my_index) # note, order not guaranteed
df.loc[idx2, ...]
Assuming my_index are the row indices you want to ignore, you could drop these where they exist in the dataframe df:
df = df.drop(my_index, errors='ignore')
Use difference:
df.loc[df.index.difference(my_index),my_feature]
Alternatively numpy.setdiff1d:
df.loc[np.setdiff1d(df.index, my_index),my_feature]
Sample:
my_index = [5,7]
df = pd.DataFrame({'A': ['a','a','a','b'], 'B': list(range(4)) }, index=[5,7,8,9])
print (df)
A B
5 a 0
7 a 1
8 a 2
9 b 3
print(df.loc[df.index.difference(my_index),'A'])
8 a
9 b
Name: A, dtype: object