【问题标题】:numpy.where with like operatornumpy.where 与 like 运算符
【发布时间】:2017-08-22 16:35:10
【问题描述】:

我想使用np.where,但需要使用通配符匹配字符串。这可能吗,或者在这种情况下最好使用其他功能吗?

df['PRODUCT'] = np.where(df['TYPE'] == '2b', 'Pencil',
                np.where(df['TYPE'] like 'I5%', 'Ruler', 0))

我尝试使用 in 运算符,但这不起作用。

df['PRODUCT'] = np.where(df['TYPE'] == '2b', 'Pencil',
                np.where('I5' in df['TYPE'], 'Ruler', 0))

【问题讨论】:

    标签: python python-2.7 pandas numpy


    【解决方案1】:

    你需要contains:

    df['PRODUCT'] = np.where(df['TYPE'] == '2b', 'Pencil',
                    np.where(df['TYPE'].str.contains('I5'), 'Ruler', 0))
    

    示例:

    df = pd.DataFrame({'TYPE':['2b','2c','I5','I5 a', 'a I5']})
    print (df)
       TYPE
    0    2b
    1    2c
    2    I5
    3  I5 a
    4  a I5
    
    df['PRODUCT'] = np.where(df['TYPE'] == '2b', 'Pencil',
                    np.where(df['TYPE'].str.contains('I5'), 'Ruler', 0))
    
    print (df)
       TYPE PRODUCT
    0    2b  Pencil
    1    2c       0
    2    I5   Ruler
    3  I5 a   Ruler
    4  a I5   Ruler
    

    如果需要只检查字符串的开头添加^:

    df['PRODUCT'] = np.where(df['TYPE'] == '2b', 'Pencil',
                    np.where(df['TYPE'].str.contains('^I5'), 'Ruler', 0))
    
    print (df)
       TYPE PRODUCT
    0    2b  Pencil
    1    2c       0
    2    I5   Ruler
    3  I5 a   Ruler
    4  a I5       0
    

    【讨论】:

    • 很高兴能帮到你!
    猜你喜欢
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2022-10-01
    • 2018-12-13
    • 2020-10-26
    相关资源
    最近更新 更多