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

Convert pandas series strings to numbers

`Following series, contains result as string of lists with values either PASS or FAIL.
Input:-

result
"[‘PASS’,’FAIL’]"
"[‘PASS’,’FAIL’,’PASS’,’FAIL’]"
"[‘FAIL’,’FAIL’]"

Output:

result
1
1
0

If any row has at-least one PASS as value then return 1 else return 0
Input:-

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

result
"[‘PASS’,’FAIL’]"
"[‘PASS’,’FAIL’,’PASS’,’FAIL’]"
"[‘FAIL’,’FAIL’]"

>Solution :

If there are lists use in statement:

df['result'] = [int('PASS' in x) for x in df['result']]
#alternative solution
df['result'] = df['result'].apply(lambda x: 'PASS' in x).astype(int)

If strings use Series.str.contains:

df['result'] = df['result'].str.contains('PASS').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