Jed
Jed

Reputation: 399

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

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'

Upvotes: 0

Views: 29

Answers (1)

mozway
mozway

Reputation: 260410

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

Upvotes: 2

Related Questions