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

如何在Python中使用Pandas将多列堆叠转换为行?

解决方案

你可以通过拆分原DataFrame的两组数据、重命名列后拼接的方式实现格式转换,具体操作如下:

  • 提取并重命名第一组(Genotype1/Grain_weight1)数据:

    df1 = df[['Genotype1', 'Grain_weight1']].rename(columns={'Genotype1': 'Genotype', 'Grain_weight1': 'Grain_weight'})
    
  • 提取并重命名第二组(Genotype2/Grain_weight2)数据:

    df2 = df[['Genotype2', 'Grain_weight2']].rename(columns={'Genotype2': 'Genotype', 'Grain_weight2': 'Grain_weight'})
    
  • 拼接两个子DataFrame并按原索引排序:

    result = pd.concat([df1, df2]).sort_index()
    

执行后result即为目标格式,输出示例:

Genotype  Grain_weight
1       CV1            25
1       CV2            29
2       CV1            26
2       CV2            32
3       CV1            30
3       CV2            33
4       CV1            31
4       CV2            32
5       CV1            29
5       CV2            30

如果偏好更简洁的写法,也可以用pd.melt结合列名匹配实现:

# 添加索引列用于分组
df['idx'] = df.index
# 转换为长格式并提取分组标识
melted = pd.melt(df, id_vars=['idx'], var_name='col', value_name='val')
melted['group'] = melted['col'].str[-1]
# 重塑为目标格式
result = melted.pivot(index=['idx', 'group'], columns='col', values='val').reset_index(level='group', drop=True)
# 重命名列并排序
result.columns = ['Genotype', 'Grain_weight']
result = result.sort_index()

内容的提问来源于stack exchange,提问作者J.K Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:15:24