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

Python DataFrame多行转多列并保留NaN值实现方法

DataFrame多列透视转换并保留NaN值

原始数据

Brand    Key    Col_Name1          Percentage   Col_Name2           Dollar_Value
A        1      Percentage_High    90           Dollar_Value_High   30000
A        1      Percentage_Low     70           Dollar_Value_Low    20000
B        2      Percentage_High    80           Dollar_Value_High   25000
B        2      Percentage_Low     60           Dollar_Value_Low    15000
C        3      Percentage_High    Nan          Dollar_Value_High   Nan
C        3      Percentage_Low     Nan          Dollar_Value_Low    Nan

期望转换结果

Brand    Key    Percentage_High   Percentage_Low    Dollar_Value_High   Dollar_Value_Low
A        1      90                70                30000               20000
B        2      80                60                25000               15000
C        3      Nan               Nan               Nan                 Nan

现有问题

当前使用pivot_table仅能处理单列,且默认会忽略全NaN的行(如Brand C):

df_pivot = df.pivot_table('Percentage', ['Brand', 'Key'], 'Col_Name1')
df_pivot.reset_index(drop=False, inplace=True)

解决方案

方法一:分别透视后合并(直观易理解)

通过分别对Percentage和Dollar_Value列做透视,设置dropna=False保留全NaN行,最后合并结果:

import pandas as pd

# 透视Percentage列,保留全NaN行
df_perc = df.pivot_table(
    values='Percentage',
    index=['Brand', 'Key'],
    columns='Col_Name1',
    dropna=False
).reset_index()

# 透视Dollar_Value列,保留全NaN行
df_dollar = df.pivot_table(
    values='Dollar_Value',
    index=['Brand', 'Key'],
    columns='Col_Name2',
    dropna=False
).reset_index()

# 合并两个结果
result = pd.merge(df_perc, df_dollar, on=['Brand', 'Key'])

方法二:单次透视多列(更简洁)

直接在pivot_table中指定多个值列,调整列名层级后得到目标格式:

import pandas as pd

# 一次性透视多列,设置dropna=False保留全NaN行
df_pivot = df.pivot_table(
    values=['Percentage', 'Dollar_Value'],
    index=['Brand', 'Key'],
    columns=['Col_Name1', 'Col_Name2'],
    dropna=False
)

# 合并列名层级,生成目标列名
df_pivot.columns = [col[1] if col[0] == 'Percentage' else col[3] for col in df_pivot.columns]

# 重置索引
result = df_pivot.reset_index()

关键说明

  • dropna=False是保留全NaN行的核心参数,默认情况下pivot_table会自动删除所有值均为NaN的分组。
  • 两种方法都能实现多列转换并保留Brand C这类全NaN的行,可根据个人习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:25:35