How do I select rows within a dataframe which start with the same phrase, without having to individually select the rows, within python?

Question:

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'

Asked By: Jed

||

Answers:

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

Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.