【发布时间】:2019-06-13 10:20:48
【问题描述】:
我想将特征“流派”散列到 6 列中,并将“出版商”特征分别散列到另外 6 列中。我想要类似下面的东西:
Genre Publisher 0 1 2 3 4 5 0 1 2 3 4 5
0 Platform Nintendo 0.0 2.0 2.0 -1.0 1.0 0.0 0.0 2.0 2.0 -1.0 1.0 0.0
1 Racing Noir -1.0 0.0 0.0 0.0 0.0 -1.0 -1.0 0.0 0.0 0.0 0.0 -1.0
2 Sports Laura -2.0 2.0 0.0 -2.0 0.0 0.0 -2.0 2.0 0.0 -2.0 0.0 0.0
3 Roleplaying John -2.0 2.0 2.0 0.0 1.0 0.0 -2.0 2.0 2.0 0.0 1.0 0.0
4 Puzzle John 0.0 1.0 1.0 -2.0 1.0 -1.0 0.0 1.0 1.0 -2.0 1.0 -1.0
5 Platform Noir 0.0 2.0 2.0 -1.0 1.0 0.0 0.0 2.0 2.0 -1.0 1.0 0.0
下面的代码做了我想做的事情
import pandas as pd
d = {'Genre': ['Platform', 'Racing','Sports','Roleplaying','Puzzle','Platform'], 'Publisher': ['Nintendo', 'Noir','Laura','John','John','Noir']}
df = pd.DataFrame(data=d)
from sklearn.feature_extraction import FeatureHasher
fh1 = FeatureHasher(n_features=6, input_type='string')
fh2 = FeatureHasher(n_features=6, input_type='string')
hashed_features1 = fh.fit_transform(df['Genre'])
hashed_features2 = fh.fit_transform(df['Publisher'])
hashed_features1 = hashed_features1.toarray()
hashed_features2 = hashed_features2.toarray()
pd.concat([df[['Genre', 'Publisher']], pd.DataFrame(hashed_features1),pd.DataFrame(hashed_features2)],
axis=1)
这适用于上述两个特征,但如果我有 40 个分类特征,那么这种方法会很乏味。还有其他办法吗?
【问题讨论】:
-
非常好的第一个问题 - 我添加了更多标签,这样它就可以暴露给具有正确技能的 ppl。
-
40 个分类特征,40 列分类数据??
-
是 40 列分类数据。
-
谢谢帕特里克·阿特纳。
标签: python pandas dataframe scikit-learn feature-extraction