python & pandas: subset dataframe with value in a list
you just pronounced it!
df[df.A.isin([2,3])]
A B
1 2 H
2 3 I
so it selects rows (df[...]
) where a value of A (df.A
) is in a given list (.isin([2,3])
)
Related videos on Youtube
Meng
2018 - Present Finished my master in Statistics. Quit machine learning. Now I am a developer. :) 2015-2017 Undergraduate Statistic student interested in machine learning and data mining. I always think of how to program easier, cleaner and faster, so I always ask questions like 'is there any simpler way to do it instead of blablabla'. People here are nice and intelligent! I will keep asking and asking and hopefully one day I am able to help others as well :D Cheers!
Updated on June 13, 2022Comments
-
Meng almost 2 years
I have a dataframe
df = pd.DataFrame({'A':[1,2,3,4],'B':['G','H','I','K']})
and I want to select rows where the value of column A is in [2,3]To do this, I write a simple for-loop:
df.loc[[ e in [2,3] for e in df.A],]
Is there any build-in function that can do this instead of using for-loops?
-
SUNDONG over 7 yearsisin() function is so useful! thanks
-
Ali.E over 2 yearswhat about if you need to check two columns?
-
jazzabeanie about 2 years@Ali.E, docs give an example of how to do this pandas.pydata.org/pandas-docs/stable/reference/api/… and also how to do is not in.