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

Python中如何将对象列表转换为行对应标题、列对应标签的稀疏矩阵

Python 对象列表转标签稀疏矩阵实现方法

方法一:使用 scikit-learn 快速实现(推荐)

依赖scikit-learn和pandas,代码量少不易出错:

from sklearn.preprocessing import MultiLabelBinarizer
import pandas as pd

# 示例数据
data = [
  {
    'title': 'title1', 'tags': ['tag1', 'tag2', 'tag3']
  },
  {
    'title': 'title2', 'tags': ['tag1']
  }
]

# 提取所有标题和对应标签列表
titles = [item['title'] for item in data]
tags_collection = [item['tags'] for item in data]

# 初始化多标签二值化器,开启稀疏矩阵输出
mlb = MultiLabelBinarizer(sparse_output=True)
# 转换得到稀疏矩阵
sparse_matrix = mlb.fit_transform(tags_collection)

# 如需查看结构化效果,可转为DataFrame验证
df = pd.DataFrame(sparse_matrix.todense(), index=titles, columns=mlb.classes_)
print(df)

输出效果和预期一致:

tag1  tag2  tag3
title1     1     1     1
title2     1     0     0

方法二:手动基于scipy构造(无sklearn依赖)

适合不想引入机器学习库的场景,可自主控制映射逻辑:

from scipy.sparse import csr_matrix
import pandas as pd

data = [
  {
    'title': 'title1', 'tags': ['tag1', 'tag2', 'tag3']
  },
  {
    'title': 'title2', 'tags': ['tag1']
  }
]

# 生成标题到行索引、标签到列索引的映射
titles = list(dict.fromkeys([item['title'] for item in data])) # 去重保留出现顺序
tags = list(dict.fromkeys([tag for item in data for tag in item['tags']]))
title2row = {t:i for i,t in enumerate(titles)}
tag2col = {t:i for i,t in enumerate(tags)}

# 收集非零元素的坐标和值
vals = []
rows = []
cols = []
for item in data:
    row_idx = title2row[item['title']]
    for tag in item['tags']:
        col_idx = tag2col[tag]
        vals.append(1)
        rows.append(row_idx)
        cols.append(col_idx)

# 构造CSR格式稀疏矩阵
sparse_matrix = csr_matrix((vals, (rows, cols)), shape=(len(titles), len(tags)))

# 查看效果
df = pd.DataFrame(sparse_matrix.todense(), index=titles, columns=tags)
print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:09:03