Home > other >  How to convert column type of a dataframe
How to convert column type of a dataframe

Time:09-06

i have a dataframe where most columns are of type "object". I want to sort some like int, date or float.

I'm trying this through a dict:

df = df.astype(
    {
        'ID': int,
        'Data': date,
        'ID_Moto': int,
        'ID_Veiculo': int,
        'Pacotes_e': int,
        'Data_de_coleta ': date,
        'Pacotes_c': int
    }
)

But it returns the following error:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

what should I do?

CodePudding user response:

Use the Int64 dtype:

df = pd.DataFrame({'col': [1,2, None]})

df = df.astype({'col': 'Int64'})

Or for automatic conversion if possible, convert_dtypes:

df = df.convert_dtypes()

Output:

    col
0     1
1     2
2  <NA>

CodePudding user response:

You could also use fillna() which turns all none values to a value of your choosing. Like this:

df = df.fillna(0)

This will convert all your 'NoneType' values to 0's and your code won't encounter any issues with those cells

  • Related