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

基于Pandas实现:匹配指定列列名并填充对应数值

使用Pandas实现列名匹配与数值填充

需求说明

  • 从DataFrame的第1列及后续列中提取列名
  • 匹配每行第0列文本中包含的列名
  • 在匹配到的列名对应的单元格中填入该列名出现的次数

输入示例

import pandas as pd

data = [['EA',0,0,0], ['col2,col2', 0, 0,0], ['col3', 0,0,0]]
df_input = pd.DataFrame(data, columns=[0, 'EA', 'col2', 'col3'])

输出示例

data = [['EA',1,0,0], ['col2,col2', 0, 2,0], ['col3', 0,0,1]]
df_output = pd.DataFrame(data, columns=[0, 'EA', 'col2', 'col3'])

实现代码

import pandas as pd

# 构造输入DataFrame
data_input = [['EA',0,0,0], ['col2,col2', 0, 0,0], ['col3', 0,0,0]]
df_input = pd.DataFrame(data_input, columns=[0, 'EA', 'col2', 'col3'])

# 复制输入数据作为输出基础
df_output = df_input.copy()

# 获取需要匹配的目标列(排除第0列)
target_columns = df_output.columns[1:]

# 逐行处理
for index, row in df_output.iterrows():
    # 拆分第0列的文本为列名列表
    matched_cols = row[0].split(',')
    # 统计每个目标列的出现次数
    col_count = {}
    for col in matched_cols:
        if col in target_columns:
            col_count[col] = col_count.get(col, 0) + 1
    # 将统计结果填入对应列
    for col, count in col_count.items():
        df_output.loc[index, col] = count

# 查看结果
print(df_output)

代码说明

  1. 复制输入DataFrame,避免直接修改原始数据
  2. target_columns筛选出第1列及之后的列名,作为匹配的目标集合
  3. 遍历每行拆分第0列文本,统计有效列名的出现次数
  4. 将统计值赋值给对应列的单元格,完成填充

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:23:17