字符串搜索功能

时间:2019-12-04 15:47:39

标签: pandas

这可行:

idocs[idocs['Message'].str.contains('No sold-to found')]

但这不是:

def msg_logic(msg):
    if msg.str.contains('No sold-to found'):
       return 'No Sold-to'
    else:
       return 'Other'

idocs['Category'] = idocs.apply(lambda x: msg_logic(x['Message']),axis=1)
print(idocs['Category'].unique())    
idocs.head()

3 个答案:

答案 0 :(得分:2)

我推荐for(...){ sender.sendPacket(packet) }

np.where

对于多种情况,请使用idocs['Category'] = (np.where(idocs['Message'].str.contains('No sold-to found'), 'No Sold-to', 'Other'))

答案 1 :(得分:1)

def msg_logic(msg):
    if 'No sold-to found' in msg:
       return 'No Sold-to'
    else:
       return 'Other'

idocs['Category'] = idocs.apply(lambda x: msg_logic(x['Message']),axis=1)
print(idocs['Category'].unique())    
idocs.head()

您的代码无法运行,因为函数中的msg是没有数据帧的字符串。

idocs['Category'] = idocs['Message'].apply(lambda x: "No Sold-to" if "No sold-to found" in x else "Other")  

答案 2 :(得分:0)

尝试一下。

idocs['Category'] = idocs['Message'].str.contains('No sold-to found')
idocs['Category'] = idocs['Category'].apply(lambda x: 'No Sold-to' if x else 'Other')