JavierSando
JavierSando

Reputation: 339

Converting dataframe column names from string to int

I have several dataframes with this structure:

df.head()
Out[7]: 
               2010        2011        2012  ...        2016        2017        2018
NUTS_ID                                      ...                                    
AT        29645.902   29562.669   29397.035  ...   30351.561   30927.367   32107.263
BE        44173.629   43092.508   44352.409  ...   44326.861   46496.095   46913.188
BG         8111.250    9808.000    8795.250  ...   10697.000   10802.369   10406.698
CZ        25778.000   24004.500   23693.500  ...   23437.068   24897.500   23535.981
DE       234388.227  226756.090  227920.837  ...  232503.925  242876.975  228012.980

[5 rows x 9 columns]

The columns' names are string. However, I need to convert them to int. I tried doing df.columns = df.columns.astype(int) but I'm getting an error: TypeError: Cannot cast Index to dtype int32. How can I fix this problem? Thanks in advance.

Upvotes: 0

Views: 500

Answers (2)

Danail Petrov
Danail Petrov

Reputation: 1875

df.columns = df.columns.astype(int)

Upvotes: 0

Ismael EL ATIFI
Ismael EL ATIFI

Reputation: 2108

df.columns = [int(s) for s in df.columns]

Upvotes: 1

Related Questions