Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

python - matching entries of a dataframe column with a list and creating a new column based on match

I am looking for a pythonic way to handle this dataframe column and list matching problem:

Here is my dataframe:

enter image description here

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 a.k.a roll_no. and insert a new column which will have a 0 for no match and 1 for match. e.g. the resulting dataframe will look like: enter image description here

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...