Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a value is in the list in selection from pandas data frame?

Looks ugly:

df_cut = df_new[              (              (df_new['l_ext']==31) |              (df_new['l_ext']==22) |              (df_new['l_ext']==30) |              (df_new['l_ext']==25) |              (df_new['l_ext']==64)              )             ] 

Does not work:

df_cut = df_new[(df_new['l_ext'] in [31, 22, 30, 25, 64])] 

Is there an elegant and working solution of the above "problem"?

like image 666
Roman Avatar asked Aug 15 '13 09:08

Roman


People also ask

How do you check if a value is in a series pandas?

isin() function check whether values are contained in Series. It returns a boolean Series showing whether each element in the Series matches an element in the passed sequence of values exactly.


2 Answers

Use isin

df_new[df_new['l_ext'].isin([31, 22, 30, 25, 64])] 
like image 180
waitingkuo Avatar answered Sep 27 '22 20:09

waitingkuo


You can use pd.DataFrame.query:

select_values = [31, 22, 30, 25, 64] df_cut = df_new.query('l_ext in @select_values') 

In the background, this uses the top-level pd.eval function.

like image 31
jpp Avatar answered Sep 27 '22 18:09

jpp