我尝试在数据框中的单个列上执行特征哈希器,但它不断给出错误 ValueError:样本不能是单个字符串。输入必须是字符串可迭代对象上的可迭代对象。
from sklearn.feature_extraction import FeatureHasher
hash_vector_size = 50
fh = FeatureHasher(n_features=hash_vector_size, input_type='string')
hashed_df = pd.DataFrame(fh.transform(X_train["Item_Identifier"]).toarray(),
columns=['H'+str(i) for i in range (hash_vector_size)])
我期待一个包含 50 列的数据框,其中的数据将被散列到其中
你就快到了:
from sklearn.feature_extraction import FeatureHasher
import pandas as pd
data = {"Item_Identifier": ["ID1", "ID2", "ID3", "ID4", "ID5"]}
X_train = pd.DataFrame(data)
hash_vector_size = 50
fh = FeatureHasher(n_features=hash_vector_size, input_type='string')
hashed_features = fh.transform([[item] for item in X_train["Item_Identifier"]])
hashed_df = pd.DataFrame(hashed_features.toarray(),
columns=['H'+str(i) for i in range(hash_vector_size)])
print(hashed_df)
这给出了
H0 H1 H2 H3 H4 H5 H6 H7 H8 H9 ... H40 H41 H42 H43 \
0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -1.0 ... 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
4 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0
H44 H45 H46 H47 H48 H49
0 0.0 0.0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0 0.0 0.0
3 0.0 0.0 0.0 0.0 0.0 0.0
4 0.0 0.0 0.0 0.0 0.0 0.0
[5 rows x 50 columns]