Home > Back-end >  How do I select rows within a dataframe which start with the same phrase, without having to individu
How do I select rows within a dataframe which start with the same phrase, without having to individu

Time:11-07

enter image description here

How do I create a column in my dataframe called 'Declined Or Hired', where a '1' is input into each row where the (Declined - Reason) Or Hire column starts with "Offer Declined -...). My code below works, however I think I've written a long solution, which could be shorter.

df.loc[(df['(Declined - Reason) Or Hire'] == 'Offer Declined - Accepted Another Offer') | (df['(Declined - Reason) Or Hire'] == 'Offer Declined - Company'), 'Declined Or Hired'] ='1'

CodePudding user response:

Use str.startswith and convert the booleans to integers with astype:

df['Declined or Hired'] = (df['(Declined - Reason) Or Hire']
                          .str.startswith('Offer Declined', na=False)
                          .astype(int)
                          )

If you want to match anywhere (not only on start), rather use str.contains

  • Related