Home > Mobile >  Pandas convert ALL columns to a int64 type
Pandas convert ALL columns to a int64 type

Time:04-23

I have the following code:

import pandas as pd

df = pd.DataFrame({'a': [2], 'b': ['1'], 'c': ['3'], 'd': [5]})
print(df.dtypes)

And obviously I get

a     int64
b    object
c    object
d     int64
dtype: object

as an output. I would like to map each of the columns to int64, but automatically - I don't want to go through all the columns manually and set each one of them to int64. Is there a one-liner or a crafty way to do it?

P.S. I know I can change the type to int64 by using pd.to_numeric(df['b']), for example. I want to do this for ALL the columns.

CodePudding user response:

You can use pandas.DataFrame.astype

df = df.astype('int64')
print(df)

a    int64
b    int64
c    int64
d    int64
dtype: object
  • Related