2016-02-12 21 views
23

我想将float64的数据框索引(行)从字符串或unicode更改为字符串。pandas - 将df.index从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 

回答

36

你可以做到这样:

# 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(熊猫所基于的库)的特性。

每个numpy的阵列具有D型细胞,这基本上是类型其元素:以这种方式,numpy的直接处理本地类型,不与Python对象,这解释了它的是如此之快。所以当你将dtype从int64改为float64时,numpy会将每个元素转换为C代码。

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

如果您想要字符串,您因此必须使用对象 dtype。但使用.astype(object)不会给你你正在寻找的答案:它会创建一个对象 dtype的索引,但将Python浮动对象放在里面。

这里,通过使用地图,我们的指数转换为具有合适功能的字符串:numpy的得到的字符串对象,并了解该指数已经有一个对象 D型,因为这是一个可以容纳字符串只D型。

+0

这对Python 3.5无效。你有什么想法,为什么? –

+2

原来的海报使用的是Python 2.在Python 3中'unicode'类型不再存在,而必须使用'str'类型(基本上,Python 2中称为“str”的字段在Python 3和'unicode'同样变成了'str')。 请参阅[此问题](http://stackoverflow.com/questions/19877306/nameerror-global-name-unicode-is-not-defined-in-python-3)以获取更多信息。 – Arthur