Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate through data frame and edit values?

Google provided me with the code:

for i in df.index:
    df.at[i, 'job'] = 0 if df.at[i, 'job'] == 'unemployed' else 1

But python says: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I’m not sure how to fix it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need to iterate over the rows. You can use apply():

df['job'] = df['job'].apply(lambda x: 0 if x == 'unemployed' else 1)

Or you can use numpy‘s where:

df['job'] = np.where(df['job']=='unemployed', 1, 0)

Or as Arne pointed out in his comment, you can convert the boolean result of the comparison to int:

df['job'] = (df.job != 'unemployed').astype(int)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading