简体   繁体   中英

Pandas convert ALL columns to a int64 type

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?

PS 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.

You can use pandas.DataFrame.astype

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

a    int64
b    int64
c    int64
d    int64
dtype: object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM