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

Use a list of same values to select rows from a dataframe

Consider the following dataframe:

df = pd.DataFrame({'Id': [1, 2, 3], 'Age': [20, 21, 22]})
df

   Id  Age
0   1   20
1   2   21
2   3   22

Now, I want to find rows in which the Id are 1 and 2. In this case, I use the following code:

df.loc[df.Id.isin([1, 2])]

and it returns:

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

   Id  Age
0   1   20
1   2   21

When I use two same Id, it returns only one row. For example when I use the following code:

df.loc[df.Id.isin([1, 1])]

it returns:

   Id  Age
0   1   20

My desired output in this case is:

   Id  Age
0   1   20
1   1   20

How can I get this output only using pandas?

>Solution :

Set Id as the index, use .loc, and reset Id back to a column:

df.set_index('Id').loc[[1, 1]].reset_index()

#    Id  Age
# 0   1   20
# 1   1   20
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