簡體   English   中英

'KeyError:' 迭代 Pandas 數據框時?

[英]'KeyError:' when iterating over pandas data frame?

我有兩個列表Y_trainY_test 目前他們持有分類數據。 每個元素要么是Blue要么是Green 它們將成為隨機森林分類器的目標。 我需要將它們編碼為 1.0s 和 0.0s。

這是一個print(Y_train)向您展示數據框的樣子。 旁邊的隨機數是因為數據已被洗牌。 Y_test是一樣的,只是更小):

183      Blue
126      Blue
1        Blue
409      Blue
575    Green
         ...   
396      Blue
192      Blue
578    Green
838    Green
222      Blue
Name: Colour, Length: 896, dtype: object

為了對此進行編碼,我將簡單地遍歷它們並將每個元素更改為它們的編碼值:

for i in range(len(Y_train)):
        if Y_train[i] == 'Blue':
            Y_train[i] = 0.0
        else:
            Y_train[i] = 1.0

但是,當我這樣做時,我得到以下信息:

Traceback (most recent call last):
  File "G:\Work\Colours.py", line 90, in <module>
    Main()
  File "G:\Work\Colours.py", line 34, in Main
    RandForest(X_train, Y_train, X_test, Y_test)
  File "G:\Work\Colours.py.py", line 77, in RandForest
    if Y_train[i] == 'Blue':
  File "C:\Users\Me\AppData\Roaming\Python\Python37\site-packages\pandas\core\series.py", line 1068, in __getitem__
    result = self.index.get_value(self, key)
  File "C:\Users\Me\AppData\Roaming\Python\Python37\site-packages\pandas\core\indexes\base.py", line 4730, in get_value
    return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
  File "pandas\_libs\index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 88, in pandas._libs.index.IndexEngine.get_value
  File "pandas\_libs\index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 992, in pandas._libs.hashtable.Int64HashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 998, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 6

奇怪的是它在不同的時間產生這個錯誤。 我已經使用標志和印刷品來查看它的進展情況。 有時它會在循環中進行多次迭代,然后其他時候它只會在中斷之前進行一兩次迭代。

我假設我不太明白你應該如何正確地迭代數據幀。 如果對這些東西有更多經驗的人可以幫助我,那就太好了。

嘗試:

 Y_train[Y_train == 'Blue']=0.0
 Y_train[Y_train == 'Green']=1.0

那應該可以解決您的問題。

如果您的標簽數量甚至超過當前示例(在您的情況下為藍色和綠色), sklearn提供了一個標簽編碼器,允許您使用

from sklearn import preprocessing 

label_encoder = preprocessing.LabelEncoder() 

# Transforms the 'column' in your dataframe df
df['column']= label_encoder.fit_transform(df['column'])

如果您使用自己的方法來標記編碼,最好創建一個單獨的編碼列而不是修改原始列。之后您可以將編碼列分配給您的數據幀。 作為您的場景的示例。

encoded = np.ones((Y_train.shape[0],1))
for i in range(Y_train.shape[0]):
        if Y_train[i] == 'Blue':
            encoded[i] = 0

請注意,這僅適用於您有兩個類別的情況。

對於多個類別,您可以使用 sklearn 或 pandas 方法。

對於多個類別

另一種方法是使用熊貓cat.codes 。您可以將熊貓系列轉換為類別並獲取類別代碼。

Y_train = pd.Series(Y_train)
encoded = Y_train.astype("category").cat.codes

您也可以使用sklearn Labelencoder對分類數據進行編碼。

from sklearn.preprocessing import  LabelEncoder 
le = LabelEncoder()
encoded = le.fit_transform(Y_train)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM