pandas - 将df.index从float64更改为unicode或string

Boo*_*d16 45 python indexing rows dataframe pandas

我想将数据帧的索引(行)从float64更改为string或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)
Run Code Online (Sandbox Code Playgroud)

错误信息:

TypeError: Setting <class 'pandas.core.index.Float64Index'> dtype to anything other than float64 or object is not supported
Run Code Online (Sandbox Code Playgroud)

Art*_*hur 71

你可以这样做:

# 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)
Run Code Online (Sandbox Code Playgroud)

至于为什么你会从你从int转换为float时有所不同,这是numpy(pandas所基于的库)的特点.

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

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

如果你想要字符串,那么你必须使用对象 dtype.但是使用.astype(object)不会给你你想要的答案:它会创建一个带有对象 dtype 的索引,但是将Python浮点对象放在里面.

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

  • 最初的海报是使用Python 2.在Python 3中不再存在`unicode`类型,而且必须使用`str`类型(基本上,Python 2中所谓的`str`在Python中称为`bytes` 3,`unicode`同样成为`str`).有关详细信息,请参阅[此问题](http://stackoverflow.com/questions/19877306/nameerror-global-name-unicode-is-not-defined-in-python-3). (3认同)

小智 5

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

    # Python 3 (pandas 0.19 or latter versions)
    df.index.astype(str, copy = False)
Run Code Online (Sandbox Code Playgroud)

  • 有时需要“df.index = df.index.astype(int)”而不是“copy=False”。 (3认同)