基于字符串特定内容用Pandas创建新列及聚合问题求助
问题描述
我有如下含编码的表格,想要实现两个目标:
- 新增两列:一列标记含
YYY的编码,另一列标记含WWW的编码(对应中间表格) - 按编码类型聚合,得到包含所有同类型编码的IDs列及对应统计总数(对应最终表格)
刚接触Python,卡在生成中间表格的环节,写的代码运行时出现KeyError: 'code'错误,求解决。
我写的错误代码
#for YYY def categorise(y): if y['Code'].str.contains('YYY'): return 1 return 0 df1['Code'] = df.apply(lambda y: categorise(y), axis=1) #for WWW def categorise(w): if w['Code'].str.contains('WWW'): return 1 return 0 df1['Code'] = df.apply(lambda w: categorise(w), axis=1)
当前表格
| Code |
|---|
| 001,ABC,123,YYY |
| 002,ABC,546,WWW |
| 003,ABC,342,WWW |
| 004,ABC,635,YYY |
期望的中间表格
| Code | Location_Y | Location_W |
|---|---|---|
| 001,ABC,123,YYY | 1 | 0 |
| 002,ABC,546,WWW | 0 | 1 |
| 003,ABC,342,WWW | 0 | 1 |
| 004,ABC,635,YYY | 1 | 0 |
期望的最终表格
| IDs | Location_Y | Location_W |
|---|---|---|
| 001,ABC,123,YYY - 004,ABC,635,YYY | 2 | 0 |
| 002,ABC,546,WWW - 003,ABC,342,WWW | 0 | 2 |
错误原因及解决方法
错误原因
apply用法错误:使用apply(axis=1)时,传入函数的参数是单行数据,y['Code']是单个字符串,不能调用Series专属的.str.contains方法。- 覆盖原列:代码中将生成的标记列赋值给了
df1['Code'],直接覆盖了原有编码列,逻辑完全错误。 - 冗余函数定义:重复定义
categorise函数,且完全没必要用自定义函数实现简单的包含判断。
正确实现步骤
步骤1:生成中间表格
直接利用Pandas的Series字符串方法高效生成标记列,无需自定义函数和apply:
import pandas as pd # 构造示例数据(如果已有DataFrame可跳过这步) data = {'Code': ['001,ABC,123,YYY', '002,ABC,546,WWW', '003,ABC,342,WWW', '004,ABC,635,YYY']} df = pd.DataFrame(data) # 生成标记列:布尔值转整数(True=1,False=0) df['Location_Y'] = df['Code'].str.contains('YYY').astype(int) df['Location_W'] = df['Code'].str.contains('WWW').astype(int) # 查看中间表格 print(df)
步骤2:生成最终表格
新增分组标识后,按分组聚合拼接编码并统计总数:
# 新增分组标识:区分YYY/WWW类型 df['group_tag'] = df['Code'].apply(lambda x: 'YYY' if 'YYY' in x else 'WWW') # 聚合操作 final_df = df.groupby('group_tag').agg( IDs=('Code', ' - '.join), Location_Y=('Location_Y', 'sum'), Location_W=('Location_W', 'sum') ).reset_index(drop=True) # 查看最终表格 print(final_df)
运行结果
中间表格输出:
Code Location_Y Location_W 0 001,ABC,123,YYY 1 0 1 002,ABC,546,WWW 0 1 2 003,ABC,342,WWW 0 1 3 004,ABC,635,YYY 1 0
最终表格输出:
IDs Location_Y Location_W 0 001,ABC,123,YYY - 004,ABC,635,YYY 2 0 1 002,ABC,546,WWW - 003,ABC,342,WWW 0 2
内容的提问来源于stack exchange,提问作者Trevor M
相关产品推荐
相关产品推荐

