我嘗試在大熊貓數據框中編碼包含分類數據("Yes"
和"No"
)的許多列。完整的數據幀包含超過400列,所以我尋找一種方法來編碼所有需要的列,而不必一一編碼它們。我使用Scikit-learn LabelEncoder
來對分類數據進行編碼。Sklearn標籤編碼多列大熊貓數據框
數據框的第一部分不必編碼,但是我正在尋找一種方法來直接編碼所有包含分類日期的所需列,而無需拆分並連接數據框。
爲了演示我的問題,我首先嚐試在數據框的一小部分上解決它。然而,卡在數據擬合和轉換的最後部分,並得到一個ValueError: bad input shape (4,3)
。我跑的代碼:
# Create a simple dataframe resembling large dataframe
data = pd.DataFrame({'A': [1, 2, 3, 4],
'B': ["Yes", "No", "Yes", "Yes"],
'C': ["Yes", "No", "No", "Yes"],
'D': ["No", "Yes", "No", "Yes"]})
# Import required module
from sklearn.preprocessing import LabelEncoder
# Create an object of the label encoder class
labelencoder = LabelEncoder()
# Apply labelencoder object on columns
labelencoder.fit_transform(data.ix[:, 1:]) # First column does not need to be encoded
完全錯誤報告:
labelencoder.fit_transform(data.ix[:, 1:])
Traceback (most recent call last):
File "<ipython-input-47-b4986a719976>", line 1, in <module>
labelencoder.fit_transform(data.ix[:, 1:])
File "C:\Anaconda\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py", line 129, in fit_transform
y = column_or_1d(y, warn=True)
File "C:\Anaconda\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 562, in column_or_1d
raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape (4, 3)
有誰知道如何做到這一點?
標籤編碼器僅支持單個列。您需要迭代您的列以編碼它們。 –
謝謝!我會研究這個問題並撰寫後續文章 – HelloBlob