将 pandas 数据框列标签从浮点数转换为整数

Posted

技术标签:

【中文标题】将 pandas 数据框列标签从浮点数转换为整数【英文标题】:Convert pandas dataframe column labels from float to integer 【发布时间】:2020-09-02 06:53:45 【问题描述】:

我有以下熊猫 dataframe 'GDP' 的 sn-p,其中列标签是浮点数。

3        2013.0        2014.0        2015.0  
4           NaN           NaN           NaN  
5  3.127550e+09           NaN           NaN  
6  1.973134e+10  1.999032e+10  2.029415e+10  
7  9.626143e+10  1.008863e+11  1.039106e+11  
8  1.254247e+10  1.279331e+10  1.312082e+10  

我尝试使用以下方法将这些浮点标签转换为整数,但没有成功:

GDP.columns = GDP.columns.astype(int)

我不断收到错误:TypeError: Cannot cast Index to dtype

然后我想将其转换为字符串(如下所示):

years = np.arange(2006, 2016).astype(str)
GDP = GDP[np.append(['Country'],years)]

因此,我的整体数据框应如下所示:

谁能帮帮我?

print(GDP.columns) 看起来像这样:

Index([       'Country',   'Country Code', 'Indicator Name', 'Indicator Code',
                 1960.0,           1961.0,           1962.0,           1963.0,
                 1964.0,           1965.0,           1966.0,           1967.0,
                 1968.0,           1969.0,           1970.0,           1971.0,
                 1972.0,           1973.0,           1974.0,           1975.0,
                 1976.0,           1977.0,           1978.0,           1979.0,
                 1980.0,           1981.0,           1982.0,           1983.0,
                 1984.0,           1985.0,           1986.0,           1987.0,
                 1988.0,           1989.0,           1990.0,           1991.0,
                 1992.0,           1993.0,           1994.0,           1995.0,
                 1996.0,           1997.0,           1998.0,           1999.0,
                 2000.0,           2001.0,           2002.0,           2003.0,
                 2004.0,           2005.0,           2006.0,           2007.0,
                 2008.0,           2009.0,           2010.0,           2011.0,
                 2012.0,           2013.0,           2014.0,           2015.0],
      dtype='object', name=3)

【问题讨论】:

print (Reducedset.columns) 是什么? @jezrael 我已经修改了上面的代码以显示 print(GDP.columns) GDP.columns 为您提供列名。试试 GDP.astype(int) @formicaman 谢谢!下面的解决方案有效! 【参考方案1】:

只转换数字列,这里是指前 4. 列之后的所有列并连接在一起:

GDP.columns = GDP.columns[:4].tolist() + GDP.columns[4:].astype(int).astype(str).tolist()

然后:

years = np.arange(2006, 2016).astype(str)
GDP = GDP[np.append(['Country'],years)]

【讨论】:

非常感谢!在python中每个列标签的数据类型应该相同吗? @Caledonian26 - 我认为不,每列应该是不同的类型。 @Caledonian26 - 但是如果需要将所有列转换为getehr,则需要相同的类型。 是的,然后我转换了:GDP.columns = GDP.columns.astype(str),然后继续使用我的公式,效果很好! 在下面查看我的整体答案!

以上是关于将 pandas 数据框列标签从浮点数转换为整数的主要内容,如果未能解决你的问题,请参考以下文章

MySQL:无法更新 JSON 列以将值从浮点数转换为整数

从浮点数转换为 QByteArray

使用舍入从浮点数转换为 uint8_t

C# 隐式运算符 MyType(int value) 自动“支持”从浮点数转换

在 C 中从浮点数转换为无符号字符

将浮点数的数据框转换为熊猫中的整数?