【问题标题】:Transform multiple categorical columns转换多个分类列
【发布时间】:2020-03-08 07:35:36
【问题描述】:

在我的数据集中,我有两个分类列,我想计算它们。这两列都包含国家,有些重叠(出现在两列中)。我想在 column1 和 column2 中为同一个国家/地区提供相同的数字。

我的数据看起来有点像:

import pandas as pd

d = {'col1': ['NL', 'BE', 'FR', 'BE'], 'col2': ['BE', 'NL', 'ES', 'ES']}
df = pd.DataFrame(data=d)
df

目前我正在转换数据,例如:

from sklearn.preprocessing import LabelEncoder
df.apply(LabelEncoder().fit_transform)

然而,这并没有区分 FR 和 ES。是否有另一种简单的方法可以得出以下输出?

o = {'col1': [2,0,1,0], 'col2': [0,2,4,4]}
output = pd.DataFrame(data=o)
output

【问题讨论】:

    标签: python python-3.x pandas scikit-learn categorical-data


    【解决方案1】:

    这是一种方法

    df.stack().astype('category').cat.codes.unstack()
    Out[190]: 
       col1  col2
    0     3     0
    1     0     3
    2     2     1
    3     0     1
    

    或者

    s=df.stack()
    s[:]=s.factorize()[0]
    s.unstack()
    Out[196]: 
       col1  col2
    0     0     1
    1     1     0
    2     2     3
    3     1     3
    

    【讨论】:

      【解决方案2】:

      您可以先将 LabelEncoder() 与数据框中的唯一值相匹配,然后再进行转换。

      le = LabelEncoder()
      le.fit(pd.concat([df.col1, df.col2]).unique()) # or np.unique(df.values.reshape(-1,1))
      
      df.apply(le.transform)
      Out[28]: 
         col1  col2
      0     3     0
      1     0     3
      2     2     1
      3     0     1
      

      【讨论】:

        【解决方案3】:

        np.uniquereturn_invesere。虽然您随后需要重建 DataFrame。

        pd.DataFrame(np.unique(df, return_inverse=True)[1].reshape(df.shape),
                     index=df.index,
                     columns=df.columns)
        
           col1  col2
        0     3     0
        1     0     3
        2     2     1
        3     0     1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-27
          • 1970-01-01
          • 1970-01-01
          • 2021-07-08
          • 1970-01-01
          • 2022-01-21
          相关资源
          最近更新 更多