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

在拆分后提取(get)第二个字符串(如果存在),否则首先提取

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

    我想根据一个短语拆分一组字符串,并得到第二个元素。但是,在不能拆分字符串的情况下,我希望保留第一个元素。下面是一个显示我当前方法的示例,默认情况下,我总是提取第二个元素:

    import pandas as pd
    df = pd.DataFrame({"a" : ["this is a (test), it is", "yet another"]})
    df["a"].str.split("\(test\)", 1).str[1]
    

    如你所见,这(错误地)给了我

    0    , it is
    1        NaN
    Name: a, dtype: object
    

    而我期望的输出应该是

    0     , it is
    1    yet another
    Name: a, dtype: object
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   jezrael    6 年前

    添加 Series.fillna 带原始列 a :

    df['b'] = df["a"].str.split("\(test\)", 1).str[1].fillna(df["a"])
    #alternative
    #df['b'] = df["a"].str.split("\(test\)", 1).str[1].combine_first(df["a"])
    print (df)
                             a            b
    0  this is a (test), it is      , it is
    1              yet another  yet another