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

Ignore invalid value in pandas dataframe column

I have created the following pandas dataframe:

import pandas as pd
import numpy as np     

ds = {'col1' : 
['1489900119000',
'้้คค,1']
}

df = pd.DataFrame(data=ds)

which looks like this:

            col1
0  1489900119000
1         ้้คค,1

I am trying to build a new column (called col2) which contains the values in col1 arranged as list. Hence the code:

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

df['col2']  = [list(map(int, str(x))) for x in df.col1]

Since there is that unexpected / invalid value at row 1 (คค,1), the code fails.

Is there any way to by-pass that row and fill it in with a default value (e.g. [9,9])? For example, the resulting dataframe would look like this:

enter image description here

>Solution :

You can use a conditional with str.isdigit:

df['col2']  = [list(map(int, str(x))) if x.isdigit() else [9,9] for x in df.col1]

Or with a custom function and try/except:

def digitize(s):
    try:
        return [int(x) for x in s]
    except ValueError:
        return [9, 9]
    
df['col2'] = df['col1'].apply(digitize)

Output:

            col1                                     col2
0  1489900119000  [1, 4, 8, 9, 9, 0, 0, 1, 1, 9, 0, 0, 0]
1         ้้คค,1                                   [9, 9]
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