I am looking for a pythonic way to handle this dataframe column and list matching problem:
Here is my dataframe:
Now, I have a list of roll_no.:
roll_no_matching = [3,5]
I want to have a matching done between this list and column B aka roll_no. and insert a new column which will have a 0 for no match and 1 for match. eg the resulting dataframe will look like:
I know how to match two dataframes based on any index column and possibly merge some columns from the two dataframes but, I am not sure how to create a new column. Any guidance here is highly appreciated.
Use Series.isin
for test membership with convert mask to integers by Series.astype
:
df['Merit_list'] = df['roll No.'].isin(roll_no_matching).astype(int)
Or Series.view
:
df['Merit_list'] = df['roll No.'].isin(roll_no_matching).view('i1')
Or by numpy.where
:
df['Merit_list'] = np.where(df['roll No.'].isin(roll_no_matching), 1, 0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.