How do I select rows within a dataframe which start with the same phrase, without having to individually select the rows, within python?
Question:
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'
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
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'
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