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

如何将DataFrame两列透视转换为0-1标记的宽表?

实现DataFrame长表转宽表(基因存在标记)

问题背景

原始DataFrame结构:

Patient   Gene
1         A
1         B
2         A
2         B
2         C
3         A
3         C

需要转换为每行对应一位患者、每列对应一个基因的宽表,存在该基因标记为1,不存在标记为0,目标格式:

GeneA   GeneB   GeneC
Patient1      1       1       0
Patient2      1       1       1 
Patient3      1       0       1

解决方案

方法一:使用pd.crosstab(简洁高效)

crosstab可直接统计行列组合的频次,刚好匹配需求(每个组合最多出现一次,频次即为1/0),之后只需调整列名和索引格式:

import pandas as pd

# 构造原始数据
df = pd.DataFrame({
    'Patient': [1, 1, 2, 2, 2, 3, 3],
    'Gene': ['A', 'B', 'A', 'B', 'C', 'A', 'C']
})

# 生成交叉表
wide_df = pd.crosstab(df['Patient'], df['Gene'])
# 给列名添加"Gene"前缀
wide_df.columns = ['Gene' + col for col in wide_df.columns]
# 给索引添加"Patient"前缀
wide_df.index = ['Patient' + str(idx) for idx in wide_df.index]

print(wide_df)

运行输出:

GeneA  GeneB  GeneC
Patient1      1      1      0
Patient2      1      1      1
Patient3      1      0      1

方法二:使用pivot_table

如果需要更灵活的聚合逻辑,可使用pivot_table,指定聚合函数返回1,缺失值填充为0:

import pandas as pd

df = pd.DataFrame({
    'Patient': [1, 1, 2, 2, 2, 3, 3],
    'Gene': ['A', 'B', 'A', 'B', 'C', 'A', 'C']
})

# 透视表转换
wide_df = df.pivot_table(
    index='Patient',
    columns='Gene',
    aggfunc=lambda x: 1,  # 存在则标记1
    fill_value=0          # 不存在补0
)
# 调整列名和索引格式
wide_df.columns = ['Gene' + col for col in wide_df.columns]
wide_df.index = ['Patient' + str(idx) for idx in wide_df.index]

print(wide_df)

输出结果与方法一完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:01:43