简体   繁体   中英

Changing dataframe column dtypes in Pandas

I am using df.columns to fetch the header of the dataframe and storing into a list. A is the list of the header value of dataframe.

A=list(df.columns)

But each element of the list are in string dtype and my header also have int value below an example of the header:

A=['ABC','1345','Acv-1234']

But I want that '1345' came to list as int dtype, not as string , like this

A=['ABC',1345,'Acv-1234']

Can anyone suggest an approach for this?

A simple way to do it is to iterate through the columns and check if the column name ( string type ) contains only numbers ( str.isdecimal() ) than convert it to int otherwise keep it as a string

In one line:

A = [int(x) if x.isdecimal() else x for x in df.columns ]

I suspect that '1345' is already a string in your df.columns before assign them to list A. You must search for the source of your df, and how the columns are assigned, in order to assign columns types.

However you can always change df.coluns as you want in any time with:

df.columns=['ABC', 1345 ,'Acv-1234']

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