1
LabelEncoder
和OneHotEncoder
對numpy數組非常有用,它將字符串轉換爲基於向量的0,1
。將熊貓數據幀的字符串列轉換爲0 1個向量
我的問題是,是否有一個整潔的API將一列熊貓數據幀轉換爲0, 1
向量?我展示了我的代碼和熊貓數據幀的原始內容123.csv
,假設我想以二進制0, 1
爲列c_a
,c_b
,c_c
,這3列中的每一列都是獨立的,我想以二進制0, 1
爲單獨獨立。
代碼,
import pandas as pd
sample=pd.read_csv('123.csv', sep=',',header=None)
print sample.dtypes
123.csv內容,
c_a,c_b,c_c,c_d
hello,python,pandas,1.2
hi,c++,vector,1.2
標籤編碼器和用於numpy的OneHotEncoder例子,
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
S = np.array(['b','a','c'])
le = LabelEncoder()
S = le.fit_transform(S)
print(S)
ohe = OneHotEncoder()
one_hot = ohe.fit_transform(S.reshape(-1,1)).toarray()
print(one_hot)
which results in:
[1 0 2]
[[ 0. 1. 0.]
[ 1. 0. 0.]
[ 0. 0. 1.]]
編輯1,試圖get_dummies
,並且它似乎結果是0.0
和1.0
(似乎float
),有沒有辦法直接轉換爲整數?
0_c_a 0_hello 0_hi 0_ho 1_c++ 1_c_b 1_java 1_python 2_c_c 2_numpy \
0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0
1 0.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0
2 0.0 0.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0
3 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 1.0
感謝HYRY,試圖'get_dummies',似乎結果是'0.0'和'1.0'(似乎'浮動'),有沒有辦法直接轉換成整數?您可以在我的試用結果中看到我的帖子更新編輯1部分。 –
感謝HYRY耐心提供幫助,將您的答覆標記爲答案,祝您週末愉快。 –