gpt4 book ai didi

python - numpy.where 与 like 运算符

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:58 25 4
gpt4 key购买 nike

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

最佳答案

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

关于python - numpy.where 与 like 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43089275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com