numpy.where与like运算符

时间:2017-03-29 09:15:52

标签: python python-2.7 pandas numpy

我想使用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))

1 个答案:

答案 0 :(得分:3)

您需要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