【问题标题】:Splitting DataFrame column from a referenced list of values从引用的值列表中拆分 DataFrame 列
【发布时间】:2020-05-20 00:58:14
【问题描述】:

我有一个带有“分类”列的 pandas DataFrame(视频游戏列表)。在该列中,我们可以找到:

  • 简单分类:“RPG”或“动作”
  • 多个分类:“动作冒险RPG Roguelike”、“动作射击游戏”

你注意到了吗?没有没有分隔符...

当然,我需要将其拆分到一个新列中,使用 WITH 分隔符(或具有每个单独元素的其他结构)。

所以

"Action Adventure RPG Roguelike" => "Action, Adventure, RPG, Roguelike"
"Action Shoot'em Up Wargame" => "Action, Shoot'em Up, Wargame"

我不能使用空格进行拆分,也不能使用大写字母(“Shoot'em Up”是 ONE 值)。

所以,在我看来,我需要创建一个函数来应用于此列,并从值列表中检查(手工制作),找到所有出现并返回带有分隔符的字符串...

类似的东西:

classification = ["Action", "Adventure", "RPG", "Roguelike", "Shoot'em Up", "Wargame"...]

def magic_tric(data):
   # do the magic, comparing each classification possible / data
   return data_separated

但我不知道该怎么做。以最有效的方式...

有人可以帮助我吗...? 提前致谢。

【问题讨论】:

    标签: python string pandas split data-cleaning


    【解决方案1】:

    这是一个想法..使用str.findall

                                    0
    0  Action Adventure RPG Roguelike
    1      Action Shoot'em Up Wargame
    
    sep = ["Action", "Adventure", "RPG", "Roguelike", "Shoot'em Up", "Wargame"]
    pattern = '|'.join(sep)
    
    
    pd.DataFrame(df[0].str.findall(pattern).tolist())
    

            0            1        2          3
    0  Action    Adventure      RPG  Roguelike
    1  Action  Shoot'em Up  Wargame       None
    

    【讨论】:

    • 是的!你是我今天的英雄:-)
    • @Richnou 也考虑接受这个答案,如果你觉得它有用..谢谢。
    猜你喜欢
    • 2018-04-07
    • 2016-02-17
    • 2015-04-11
    • 2020-07-28
    • 2021-07-12
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多