【问题标题】:Convert classes to numeric in a pandas dataframe在熊猫数据框中将类转换为数字
【发布时间】:2018-05-15 16:04:35
【问题描述】:

我正在做一个基于这个 Kaggle 数据集的项目:https://www.kaggle.com/rush4ratio/video-game-sales-with-ratings/data,我需要将数据放入 kNN 模型中,但是在当前状态下无法完成,因为我需要将字符串值转换为整数.

get_dummies 并不理想,因为数据集中有大量分类数据,并且会创建数千列。我正在寻找一种将字符串转换为数字表示的方法,例如:

Platform || Critic_Score || Publisher || Global_Sales
Wii      ||      73      ||  Nintendo ||  53
Wii      ||      86      ||  Nintendo ||  60
PC       ||      80      ||Activision ||  30
PS3      ||      74      ||Activision ||  35
Xbox360  ||      81      ||   2K      ||  38

我想变成这样:

Platform || Critic_Score || Publisher || Global_Sales
  1      ||      73      ||     1     ||  53
  1      ||      86      ||     1     ||  60
  2      ||      80      ||     2     ||  30
  3      ||      74      ||     2     ||  35
  4      ||      81      ||     3     ||  38

我正在使用 Python 3。

谢谢。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    您可以使用标签编码器 [https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html]

    from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    le.fit(df['Platform'])
    df['Platform']=le.transform(df['Platform'])
    le.fit(df['Publisher'])
    df['Publisher']=le.transform(df['Publisher'])
    print(df)
    

    这会将转换字符串转换为数字表示

    【讨论】:

      【解决方案2】:

      我觉得你需要factorize:

      df['Platform'] = pd.factorize(df['Platform'])[0] + 1
      df['Publisher'] = pd.factorize(df['Publisher'])[0] + 1
      print (df)
         Platform  Critic_Score  Publisher  Global_Sales
      0         1            73          1            53
      1         1            86          1            60
      2         2            80          2            30
      3         3            74          2            35
      4         4            81          3            38
      

      cols = ['Platform', 'Publisher']
      df[cols] = df[cols].apply(lambda x: pd.factorize(x)[0] + 1)
      
      print (df)
         Platform  Critic_Score  Publisher  Global_Sales
      0         1            73          1            53
      1         1            86          1            60
      2         2            80          2            30
      3         3            74          2            35
      4         4            81          3            38
      

      【讨论】:

      • 感谢您的帮助,我试过了,但是我收到了以下错误消息:C:\Users\Josh Charig\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: A value is试图在数据帧的切片副本上设置。尝试改用 .loc[row_indexer,col_indexer] = value 查看文档中的注意事项:pandas.pydata.org/pandas-docs/stable/… """启动 IPython 内核的入口点。此外,真正的 DF 是否有很多包含文本的列,是否存在一次改变它们的方法?
      • 检查编辑的答案。我想问题出在this,所以需要copy
      猜你喜欢
      • 2018-07-14
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 2021-08-21
      相关资源
      最近更新 更多