I have a dataframe df of multiple variables, with a number of irregularly indexed entries.
Let’s say like this:
X Y
0 60.0 0
1 63.0 10
4 80.0 10
5 46.0 1
9 73.0 10
[5 rows x 2 columns]
Now, say that I have a list of externally provided indices, indices, like:
indices = [0, 2, 4, 6, 9, 11]
How can I select all entries of df['X'] which are part of the indices? My desired output is
X
0 60.0
4 80.0
9 73.0
If I merely try to call df['X'][indices], Python rightfully complains:
KeyError: '[2, 6, 11] not in index'
Is there a simple way to do this?
>Solution :
Use Index.isin():
print(df.loc[df.index.isin(indices), 'X'])
0 60.0
4 80.0
9 73.0
Name: X, dtype: float64