You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法使用np.where与str.contains进行类别分配?

交易数据分类赋值报错修复方案

错误根源

你用df['Description'].str.contains()时,错误地把多个关键词直接当参数传了。str.contains()的第一个参数pat只能接受单个正则表达式字符串,后面的参数是case(布尔值,控制是否区分大小写)、flags这类配置项。你传的第二个关键词被当成了case参数,而字符串和正则标识位做位运算(&)时,就触发了TypeError。

修正后的代码

要匹配多个关键词,得用正则的竖线|把它们连起来,表示“或”的逻辑。如果关键词里有空格(比如vending machine),直接保留就行,正则能识别。

import numpy as np
import pandas as pd

# 示例数据(如果已有DataFrame可跳过这部分)
data = {
    'Date': ['8/11/2023', '8/14/2023', '8/14/2023', '8/14/2023', '8/15/2023'],
    'Description': ['vending machine', 'christianacare', 'shakeshack', 'capitalone', 'nordproducts'],
    'Amount': [-2.40, -155.00, -33.56, -317.14, -18.28],
    'Category': ['unassigned']*5
}
df = pd.DataFrame(data)

# 批量分配交易类别
# Bills
df['Category'] = np.where(df['Description'].str.contains('christianacare|capitalone|usaa|zelle'), 'Bills', df['Category'])
# Food
df['Category'] = np.where(df['Description'].str.contains('vending machine|tacobell|shakeshack|univlqr|gridiron|starbucks'), 'Food', df['Category'])
# Shopping
df['Category'] = np.where(df['Description'].str.contains('amazon'), 'Shopping', df['Category'])
# Services
df['Category'] = np.where(df['Description'].str.contains('coursera|empowerme|albert|apple|peacock|nordproducts|patreon'), 'Services', df['Category'])
# Entertainment
df['Category'] = np.where(df['Description'].str.contains('playstation|microsoft'), 'Entertainment', df['Category'])
# Transport
df['Category'] = np.where(df['Description'].str.contains('parkmobile'), 'Transport', df['Category'])

运行结果

执行后Category列会被正确填充:

DateDescriptionAmountCategory
08/11/2023vending machine-2.40Food
18/14/2023christianacare-155.00Bills
28/14/2023shakeshack-33.56Food
38/14/2023capitalone-317.14Bills
48/15/2023nordproducts-18.28Services

优化小技巧

如果关键词列表很长,手动写竖线容易出错,可以用'|'.join(列表)自动生成正则字符串,比如:

bills_keywords = ['christianacare', 'capitalone', 'usaa', 'zelle']
df['Category'] = np.where(df['Description'].str.contains('|'.join(bills_keywords)), 'Bills', df['Category'])

这样更方便维护,也不容易写错。

内容的提问来源于stack exchange,提问作者Jake Hatten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:02:02