1

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:

   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?

1 Answer 1

3

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.