首页 > 解决方案 > 将数据框列名从字符串转换为 int

问题描述

我有几个具有这种结构的数据框:

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]

列的名称是string. 但是,我需要将它们转换为int. 我试着做df.columns = df.columns.astype(int),但我得到一个错误:TypeError: Cannot cast Index to dtype int32。我该如何解决这个问题?提前致谢。

标签: pythonpandas

解决方案


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

推荐阅读