How to test if a string contains one of the substrings in a list, in pandas?

后端 未结 3 1914
野的像风
野的像风 2020-11-22 13:06

Is there any function that would be the equivalent of a combination of df.isin() and df[col].str.contains()?

For example, say I have the s

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 13:28

    Here is a one line lambda that also works:

    df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)
    

    Input:

    searchfor = ['og', 'at']
    
    df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])
    
       col1  col2
    0   cat 1000.0
    1   hat 2000000.0
    2   dog 1000.0
    3   fog 330000.0
    4   pet 330000.0
    

    Apply Lambda:

    df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)
    

    Output:

        col1    col2        TrueFalse
    0   cat     1000.0      1
    1   hat     2000000.0   1
    2   dog     1000.0      1
    3   fog     330000.0    1
    4   pet     330000.0    0
    

提交回复
热议问题