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

基于字符串特定内容用Pandas创建新列及聚合问题求助

问题描述

我有如下含编码的表格,想要实现两个目标:

  1. 新增两列:一列标记含YYY的编码,另一列标记含WWW的编码(对应中间表格)
  2. 按编码类型聚合,得到包含所有同类型编码的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

期望的中间表格

CodeLocation_YLocation_W
001,ABC,123,YYY10
002,ABC,546,WWW01
003,ABC,342,WWW01
004,ABC,635,YYY10

期望的最终表格

IDsLocation_YLocation_W
001,ABC,123,YYY - 004,ABC,635,YYY20
002,ABC,546,WWW - 003,ABC,342,WWW02

错误原因及解决方法

错误原因

  1. apply用法错误:使用apply(axis=1)时,传入函数的参数是单行数据,y['Code']是单个字符串,不能调用Series专属的.str.contains方法。
  2. 覆盖原列:代码中将生成的标记列赋值给了df1['Code'],直接覆盖了原有编码列,逻辑完全错误。
  3. 冗余函数定义:重复定义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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:01:13