Daru Ruby Gem-如何将分类变量转换为二进制变量

时间:2018-12-02 22:21:49

标签: ruby dataframe rubygems data-analysis

我有以下Daru数据框,其分类变量名为search_term

home,search_term,bought
0,php,1
0,java,1
1,php,1
...

我想将其转换为带有二进制列的Daru数据框,例如:

home,php,java,bought
0,1,0,1
0,0,1,1
1,1,0,1
...

我找不到实现它的方法。我知道在Python的Panda中是可行的,但我想将Ruby与Darus宝石一起使用。

谢谢。

1 个答案:

答案 0 :(得分:0)

根据blog post机器学习库的作者Yoshoku编写的Rumale,您可以这样做:

train_df['IsFemale'] = train_df['Sex'].map { |v| v == 'female' ? 1 : 0 }

Rumale的标签编码器对于分类变量也很有用。

require 'rumale'
encoder = Rumale::Preprocessing::LabelEncoder.new
labels = Numo::Int32[1, 8, 8, 15, 0]
encoded_labels = encoder.fit_transform(labels)
# Numo::Int32#shape=[5]
# [1, 2, 2, 3, 0]

Rumale :: Preprocessing :: OneHotEncoder

encoder = Rumale::Preprocessing::OneHotEncoder.new
labels = Numo::Int32[0, 0, 2, 3, 2, 1]
one_hot_vectors = encoder.fit_transform(labels)
# > pp one_hot_vectors
# Numo::DFloat#shape[6, 4]
# [[1, 0, 0, 0],
#  [1, 0, 0, 0],
#  [0, 0, 1, 0],
#  [0, 0, 0, 1],
#  [0, 0, 1, 0],
#  [0, 1, 0, 0]]

但是,Daru :: Vector和Numo :: NArray的转换需要使用to_a

encoder = Rumale::Preprocessing::LabelEncoder.new
train_df['Embarked'] = encoder.fit_transform(train_df['Embarked'].to_a).to_a