熊猫-将df.index从float64更改为unicode或字符串

发布于 2021-01-29 15:09:35

我想将数据框的索引(行)从float64更改为字符串或unicode。

我认为这会起作用,但显然不会:

#check type
type(df.index)
'pandas.core.index.Float64Index'

#change type to unicode
if not isinstance(df.index, unicode):
    df.index = df.index.astype(unicode)

错误信息:

TypeError: Setting <class 'pandas.core.index.Float64Index'> dtype to anything other than float64 or object is not supported
关注者
0
被浏览
76
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以这样操作:

    # for Python 2
    df.index = df.index.map(unicode)
    
    # for Python 3 (the unicode type does not exist and is replaced by str)
    df.index = df.index.map(str)
    

    至于为什么将处理方式从int转换为float的原因不同,那就是numpy的特殊性(pandas所基于的库)。

    每个numpy数组都有一个 dtype ,它基本上是其元素的 机器 类型:以这种方式, numpy直接处理本机类型
    ,而不处理Python对象,这说明了它是如此之快。因此,当您将dtype从int64更改为float64时,numpy将强制转换C代码中的每个元素。

    还有一个特殊的dtype: object ,它将基本上提供指向Python对象的指针。

    如果要使用字符串,则必须使用 对象 dtype。但是,使用.astype(object)不会给您所要的答案:它将创建带有 对象
    dtype的索引,但是将Python float对象放入其中。

    在这里,通过使用map,我们使用适当的函数将索引转换为字符串:numpy获取字符串对象,并了解索引必须具有 对象
    dtype,因为这是唯一可以容纳字符串的dtype。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看