2016-01-08 134 views
1

Python 2.7,numpy,以一系列因子的形式創建關卡。Python:如何將字符串數組轉換爲因子列表

我有一個列出獨立變量的數據文件,最後一列表示類。例如:

2.34,4.23,0.001, ... ,56.44,2.0,"cloudy with a chance of rain" 

使用numpy,我將所有數字列讀入矩陣,並將最後一列讀入數組中,我稱之爲「類」。事實上,我不提前知道類名,所以我不想使用字典。我也不想使用熊貓。這是問題的一個例子:

classes = ['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd'] 
type (classes) 
<type 'list'> 
classes = numpy.array(classes) 
type(classes) 
<type 'numpy.ndarray'> 
classes 
array(['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd'], 
     dtype='|S1') 
# requirements call for a list like this: 
# [0, 1, 2, 2, 1, 0, 3] 

注意,目標類可能非常稀疏,例如,「Z」,或許在1出近100,000例。還要注意,這些類可以是任意文本字符串,例如科學名稱。

我使用Python 2.7與numpy,我堅持我的環境。此外,數據已經過預處理,所以它的縮放和所有值都是有效的 - 我不想在處理數據之前再次預處理數據以提取唯一類並創建字典。我真正在尋找的是Python中等效於R中參數stringAsFactors的Python,它在腳本讀取數據時自動將字符串向量轉換爲因子向量。

不要問我爲什麼我使用Python而不是R - 我按照我所說的去做。

謝謝,CC。

回答

4

你可以使用np.uniquereturn_inverse=True返回兩個獨特的類名和一組相應的整數索引:

import numpy as np 

classes = np.array(['a', 'b', 'c', 'c', 'b', 'a', 'a', 'd']) 

classnames, indices = np.unique(classes, return_inverse=True) 

print(classnames) 
# ['a' 'b' 'c' 'd'] 

print(indices) 
# [0 1 2 2 1 0 0 3] 

print(classnames[indices]) 
# ['a' 'b' 'c' 'c' 'b' 'a' 'a' 'd'] 

類的名字將在詞彙順序進行排序。

+0

謝謝。我覺得這很容易,但我發現所有的答案都需要創建一本詞典。最後一點(在問題中沒有提到)是這樣的:「indices.astype('S10')」將整數值轉換爲真實類別,這是我需要用於分類例程。你的答案完美無缺。再次感謝你。 – user1483288

相關問題