【问题标题】:Vectorizing / Contrasting a Dataframe with Categorical Variables将数据框与分类变量矢量化/对比
【发布时间】:2014-11-09 12:46:34
【问题描述】:

假设我有一个如下数据框:

      A      B
0   bar    one
1   bar  three
2  flux    six
3   bar  three
4   foo   five
5  flux    one
6   foo    two

我想在上面申请dummy-coding contrasting 以便我得到:

    A    B
0   0    0
1   0    2
2   1    1
3   0    2
4   2    3
5   1    0
6   2    4

(即将每列的每个唯一值映射到不同的整数)。

我曾尝试使用 scikit-learn 的 DictVectorizer,但我得到了:

> from sklearn.feature_extraction import DictVectorizer as DV
> vectorizer        = DV( sparse = False )
> dict_to_vectorize = df.T.to_dict().values()
> df_vec            = vectorizer.fit_transform(dict_to_vectorize )
> df_vec
array([[ 1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.]])

这是因为 scikit-learn 的 DictVectorizer 旨在输出 one-of-K 编码。我想要的是一个简单的编码(每个变量一列)。

如何使用 scikit-learn 和/或 pandas 做到这一点?除此之外,还有其他 Python 包可以帮助解决一般的contrasting methods 问题吗?

【问题讨论】:

标签: python pandas scikit-learn statsmodels


【解决方案1】:

你可以使用pd.factorize:

In [124]: df.apply(lambda x: pd.factorize(x)[0])
Out[124]: 
   A  B
0  0  0
1  0  1
2  1  2
3  0  1
4  2  3
5  1  0
6  2  4

【讨论】:

    【解决方案2】:

    patsy 包提供了您需要的所有对比(以及制作更多对比的能力)。 [1] AFAIK,statsmodels 是目前唯一使用 patsy 公式框架的统计包。 [2, 3]。

    [1]https://patsy.readthedocs.org/en/latest/API-reference.html#handling-categorical-data

    [2]http://statsmodels.sourceforge.net/devel/contrasts.html

    [3]http://statsmodels.sourceforge.net/devel/example_formulas.html

    【讨论】:

    【解决方案3】:

    当您调用DictVectorizer 时,您会得到虚拟编码。你得到的整数编码实际上是不同的:

    • sklearn.preprocessing.LabelBinarizerDictVectorizer 提供虚拟编码(如 pandas.get_dummies
    • sklearn.preprocessing.LabelEncoder 给出整数分类编码(如pandas.factorize

    【讨论】:

      猜你喜欢
      • 2015-02-26
      • 2017-06-21
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多