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

pandas - change df.index from float64 to unicode or string

我想将数据帧的索引(行)从 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

你可以这样做:

# 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,它基本上是其元素的 machine 类型:以这种方式,numpy 直接处理原生类型 ,而不处理 Python 对象,这解释了它为何如此之快。因此,当您将 dtype 从 int64 更改为 float64 时,numpy 将转换 C 代码中的每个元素。

还有一个特殊的数据类型:object,它基本上会提供一个指向 Python 对象的指针。

如果你想要字符串,你必须使用 object dtype。但是使用 .astype(object) 不会给你你正在寻找的答案:它会创建一个索引 object dtype,但把 Python float objects inside.

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

对于 python 3 和 pandas 0.19 或更高版本,我发现以下版本对我来说很好

    # Python 3 (pandas 0.19 or latter versions)
    df.index.astype(str, copy = False)

对我来说,这个效果最好:

df.index = df.index.astype('int64')

其中int64可以改成其他类型