为何无法使用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列会被正确填充:
| Date | Description | Amount | Category | |
|---|---|---|---|---|
| 0 | 8/11/2023 | vending machine | -2.40 | Food |
| 1 | 8/14/2023 | christianacare | -155.00 | Bills |
| 2 | 8/14/2023 | shakeshack | -33.56 | Food |
| 3 | 8/14/2023 | capitalone | -317.14 | Bills |
| 4 | 8/15/2023 | nordproducts | -18.28 | Services |
优化小技巧
如果关键词列表很长,手动写竖线容易出错,可以用'|'.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
相关产品推荐
相关产品推荐

