统计DataFrame的CPT列中字典各类别代码的总出现次数
问题解决方法
核心问题分析
你的测试代码返回0的原因通常是以下几点:
- 字符串格式不统一:CPT列的条目可能带有前后空格(比如
' 99212 '),导致和你定义的'99212'无法匹配 - 类型不匹配:字典里的CPT代码是整数(如
99212),但DataFrame的CPT列是字符串类型,或者反过来 str.count的局限性:该方法会匹配子串(比如'992120'也会被统计),而你需要的是精确匹配整个条目
分步解决方案
1. 先清洗CPT列
先处理常见的格式问题,确保条目干净:
import pandas as pd # 去除字符串前后空格,统一格式 df['CPT'] = df['CPT'].str.strip() # 可选:如果CPT列实际是整数类型(但显示为object),可以转成字符串统一类型 # df['CPT'] = df['CPT'].astype(str)
2. 单个代码测试(修正你的测试代码)
用精确匹配替代str.count,确保统计准确:
nonop = ['99212', '99234'] # 统计每个代码的精确出现次数 counts = {code: (df['CPT'] == code).sum() for code in nonop} df2 = pd.Series(counts) print(df2)
3. 统计字典中每个类别的总次数
针对整个billable字典,批量统计每个类别的总出现次数:
# 把字典里的所有整数代码转成字符串(和CPT列类型统一) billable_str = { category: [str(code) for code in codes] for category, codes in billable.items() } # 遍历每个类别,统计总次数 category_total = {} for category, codes in billable_str.items(): # 统计CPT列中属于该类别任意代码的行数总和 total = df['CPT'].isin(codes).sum() category_total[category] = total # 转成Series输出,更直观 result = pd.Series(category_total) print(result)
特殊情况处理:CPT列包含多个代码
如果你的CPT列是用逗号分隔的多个代码(比如'99212,99234'),需要先拆分再统计:
# 拆分多代码条目并展开成单行一个代码 df_exploded = df['CPT'].str.split(',', expand=True).stack().reset_index(level=1, drop=True).str.strip() # 再用之前的方法统计 category_total = {} for category, codes in billable_str.items(): total = df_exploded.isin(codes).sum() category_total[category] = total result = pd.Series(category_total) print(result)
内容的提问来源于stack exchange,提问作者Patrick Murphy
相关产品推荐
相关产品推荐

