vendredi 24 avril 2020

How to combine startswith and IF for pandas

I am trying to do 2 things - 1st use a startswith in a df to identify which rows contain the condition, and 2nd add a specific TAG to a column. I have been able to do both things correctly but separately - but unsuccessful in combining.

This is an example of the content in the interest column df 'PartNumber' (GLO, GLOA, GLO1, GLOA2, GLO9, etc) the common denominator is the "GLO" and I want the tag to be added "GLO Series".

This code successfully can ID the rows that have the starting condition

search = 'GLO'
search_series = df['PartNumber'].str.startswith(search, na= False)
df[search_series] 

This code successfully can ID the row that has the specific condition - I know it is because of the '=='. The challenge is that I have to call out the specific part, which is what I do not know all values, hence my attempt to do the 'startswith'

df.loc[(df['PartNumber']== 'GLOA2'),'TAG_2']='Glo Series'
print (df)

I tried to combine both which did not work.

I am trying to achieve once completed a kind of "If this / then that" for several conditions summarized as follows:

df [PartNumber] used to ID set conditions-based on starting characters ('GLO', 'FL0', 'MOW') depending on this then a value would be placed in a set column resulting in ('Glo series', 'Flo series', 'Mow series')

Aucun commentaire:

Enregistrer un commentaire