Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select all available indices in a dataframe column in Python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading