2016-02-12 51 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