【问题标题】:How to remove lists in a column of a pandas data frame for converting categorical values to numerical values [duplicate]如何删除熊猫数据框列中的列表以将分类值转换为数值[重复]
【发布时间】:2019-10-01 14:45:11
【问题描述】:

我正在尝试使用 pd.get_dummies() 函数将分类特征转换为数值,但问题是我有一个包含列表的列。顺便说一下,这是类型列。

0     ['Action', 'Adventure', 'Comedy', 'Drama', 'Sc...

1     ['Action', 'Drama', 'Mystery', 'Sci-Fi', 'Space']

2     ['Action', 'Sci-Fi', 'Adventure', 'Comedy', 'D...

3     ['Action', 'Magic', 'Police', 'Supernatural', ...

4     ['Adventure', 'Fantasy', 'Shounen', 'Supernatu...

我已经尝试了解决此问题的 stackoverflow 上的所有答案。没有任何效果

我希望输出是

0    'Action', 'Adventure', 'Comedy', 'Drama', 'Sc...

1    'Action', 'Drama', 'Mystery', 'Sci-Fi', 'Space'

2    'Action', 'Sci-Fi', 'Adventure', 'Comedy', 'D...

3    'Action', 'Magic', 'Police', 'Supernatural', ...

4    'Adventure', 'Fantasy', 'Shounen', 'Supernatu...

这样我就可以使用 get_dummies 来创建假人了。请帮忙!

【问题讨论】:

  • df['genre'] = df['genre'].str.join(', ')
  • 问题与machine-learning 无关 - 请不要向无关标签发送垃圾邮件(已删除)。

标签: python pandas dataframe data-cleaning


【解决方案1】:

你可以在 0.25 以上的 pandas 中使用 explode 来做到这一点

d = {"genre":[['Action', 'Adventure', 'Comedy', 'Drama'],  
 ['Action', 'Drama', 'Mystery', 'Sci-Fi', 'Space'],  
 ['Action', 'Sci-Fi', 'Adventure', 'Comedy'],  
 ['Action', 'Magic', 'Police', 'Supernatural'],    
 ['Adventure', 'Fantasy', 'Shounen', 'Supernatu']]}

df = pd.DataFrame(d)
pd.get_dummies(df.explode("genre").pivot(columns="genre", values="genre"))

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2019-05-25
    相关资源
    最近更新 更多