代码之家  ›  专栏  ›  技术社区  ›  Alan

熊猫:上次出现时分割字符串

  •  1
  • Alan  · 技术社区  · 6 年前

    熊猫有str.rsplit公司以及结构分区功能。

    如果我尝试:

    df_client["Subject"].str.rsplit("-", 1)
    

    我明白了

    0[活动-位置,用户代码]

    如果我尝试

    df_client["Subject"].str.rpartition("-")
    

          0            1      2   
    

    0活动-位置-用户代码

    如果我这样做了

    df_client["Subject"].str.rpartition("-")[2]
    

    我明白了

    这正是我想要的。

    对我来说,str.rsplit公司似乎不直观。

    在获得拆分字符串的列表之后,我将如何选择所需的单个项?

    2 回复  |  直到 6 年前
        1
  •  7
  •   jezrael    6 年前

    我想我们需要 indexing by str 使用iterables:

    #select last lists 
    df_client["Subject"].str.rsplit("-", 1).str[-1]
    #select second lists
    df_client["Subject"].str.rsplit("-", 1).str[1]
    

    如果性能很重要,请使用 list comprehension :

    df_client['last_col'] = [x.rsplit("-", 1)[-1] for x in df_client["Subject"]]
    print (df_client)
                          Subject  last_col
    0  Activity-Location-UserCode  UserCode
    1  Activity-Location-UserCode  UserCode
    
        2
  •  -1
  •   Andrey Portnoy    6 年前

    使用 expand=True :

    df_client["Subject"].str.split('-', expand=True)[2]