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

Python pandas DataFrame按行列名包含关系填充单元格为1

Pandas层级标签前缀匹配填充实现方法

你可以通过字符串前缀判断逻辑快速实现需求,不需要复杂的逐单元格遍历,以下是可直接运行的实现代码:

  • 第一步:导入依赖并初始化全0 DataFrame
import pandas as pd
import numpy as np

# 定义层级标签列表
labels = ["L-1", "L-1-1", "L-1-2", "L-1-3", "L-2", "L-2-1", "L-2-2", "L-2-3"]
# 构造初始全0结构的DataFrame
df = pd.DataFrame(0, index=labels, columns=labels)
  • 第二步:执行前缀匹配填充
    推荐使用向量化实现,性能远高于逐单元格循环,适配更大规模的标签场景:
# 将行索引、列名转为可广播的数组格式
row_tags = df.index.to_numpy().reshape(-1, 1)
col_tags = df.columns.to_numpy().reshape(1, -1)
# 批量生成匹配掩码:列名以对应行标签为前缀时为True
match_mask = np.vectorize(lambda row, col: col.startswith(row))(row_tags, col_tags)
# 掩码转为0/1值覆盖原DataFrame
df.loc[:, :] = match_mask.astype(int)

如果标签量级很小,也可以用可读性更高的简单循环写法:

for row in df.index:
    df.loc[row] = [1 if col.startswith(row) else 0 for col in df.columns]
  • 结果验证
    运行代码后得到的输出和预期完全一致:
L-1  L-1-1  L-1-2  L-1-3  L-2  L-2-1  L-2-2  L-2-3
L-1      1      1      1      1    0      0      0      0
L-1-1    0      1      0      0    0      0      0      0
L-1-2    0      0      1      0    0      0      0      0
L-1-3    0      0      0      1    0      0      0      0
L-2      0      0      0      0    1      1      1      1
L-2-1    0      0      0      0    0      1      0      0
L-2-2    0      0      0      0    0      0      1      0
L-2-3    0      0      0      0    0      0      0      1

匹配规则说明:核心调用Python字符串原生startswith()方法做前缀判断,天然满足三个匹配要求:标签和自身完全匹配时返回1、下级标签(带-x后缀的子节点)匹配上级前缀时返回1、无关联标签返回0,不需要额外写字符串拆分逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 09:01:09