【问题标题】:Extract string column in multiple columns在多列中提取字符串列
【发布时间】:2020-12-17 17:13:32
【问题描述】:

我有下一个df:

Match                       Count
Asren_Blue_Coached           879
Asren_Blue_NotCoached        721
Asren_RED_Coached            6567
Asren_RED_NotCoached         764
Asren_White_Coached          762
Asren_White_NotCoached       431
Asren_Yellow_Coached         375
Asren_Yellow_NotCoached      412
Hrew_Blue_Coached            689
Hrew_Blue_NotCoached         634
...

我想添加三个新列,

“匹配”列中下划线前的每个单词一列

因此,预期的输出如下所示:

Match                       NewCol1   NewCol2    NewCol3      Count    
Asren_Blue_Coached           Asren      Blue     Coached       879      
Asren_Blue_NotCoached        Asren      Blue     NotCoached    721
Asren_RED_Coached            Asren      RED      Coached       6567
Asren_RED_NotCoached         Asren      RED      NotCoached    764
Asren_White_Coached          Asren      White    Coached       762
Asren_White_NotCoached       Asren      White    NotCoached    431
Asren_Yellow_Coached         Asren      Yellow   Coached       375
Asren_Yellow_NotCoached      Asren      Yellow   NotCoached    412
Hrew_Blue_Coached            Hrew       Blue     Coached       689
Hrew_Blue_NotCoached         Hrew       Blue     NotCoached    634
...

你知道我该怎么做吗?

我正在 Jupyter 中使用 pandas

【问题讨论】:

    标签: pandas slice extract


    【解决方案1】:

    您可以使用str.split,并将返回值分配给您希望命名的3列,并将delimiter指定为“_”

    见下文:

    df[['NewCol1', 'NewCol2','NewCol3']] = df['Match'].str.split('_', expand=True)
    

    打印你想要的输出:

    print(df)
                         Match  Count NewCol1 NewCol2     NewCol3
    0       Asren_Blue_Coached    879   Asren    Blue     Coached
    1    Asren_Blue_NotCoached    721   Asren    Blue  NotCoached
    2        Asren_RED_Coached   6567   Asren     RED     Coached
    3     Asren_RED_NotCoached    764   Asren     RED  NotCoached
    4      Asren_White_Coached    762   Asren   White     Coached
    5   Asren_White_NotCoached    431   Asren   White  NotCoached
    6     Asren_Yellow_Coached    375   Asren  Yellow     Coached
    7  Asren_Yellow_NotCoached    412   Asren  Yellow  NotCoached
    8        Hrew_Blue_Coached    689    Hrew    Blue     Coached
    9     Hrew_Blue_NotCoached    634    Hrew    Blue  NotCoached
    

    【讨论】:

      【解决方案2】:

      您可以使用Series.str.split() 在分隔符上拆分列。然后只需标记expand=True 即可获取新列而不是列表。

      df["Match"].str.split("_", expand=True)
      

      【讨论】:

        猜你喜欢
        • 2018-12-06
        • 2021-11-07
        • 2016-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        相关资源
        最近更新 更多