Home > Net >  Convert values within column to a specific type, despite column containing nulls
Convert values within column to a specific type, despite column containing nulls

Time:06-27

Looking to convert values within column to a specific type, despite column containing nulls. The column I wish to convert is ['id'] and this contains a mix of values labeled as string as well as null values. I wish to convert all the values to int within this column.

Data

    id  type    date
    1   yes     Q1
    1   yes     Q2
        maybe   Q3
        no      Q4
    5   no      Q1
    5   ok      Q2

Desired

    id  type    date
    1   yes     Q1
    1   yes     Q2
        maybe   Q3
        no      Q4
    5   no      Q1
    5   ok      Q2

Doing

df["id"] = df["id"].astype('int64')

However, because column id contains nulls, I am seeing an error. I wish to convert all the values to int within this column. Any suggestion is appreciated. Thank you

CodePudding user response:

Try this:

df = pd.DataFrame()
df["id"] = [1, "10", None, None, 5, 5]
df.id = df.id.astype(int, errors="ignore")
df.id

Print out:

0       1
1      10
2    None
3    None
4       5
5       5
  • Related