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?
CodePudding user response:
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