如何调整Pandas pivot结果,得到目标结构的DataFrame?
问题与解决方案
问题
原始Pandas DataFrame结构:
datecreated timestamp value 2022-11-15 1 4000 2022-11-15 2 3900 2022-11-15 3 3850 2022-11-15 4 3810 2022-11-15 5 3790
期望转换为目标格式:
datecreated 1 2 3 4 5 0 2022-11-15 4000 3900 3850 3810 3790
尝试df = df.pivot(index='datecreated', columns='timestamp', values='value')后得到带列层级名称的结果,执行reset_index()后数值变为浮点数,不符合预期。
解决方案
执行以下代码即可得到目标格式:
# 执行 pivot 转换 df_pivoted = df.pivot(index='datecreated', columns='timestamp', values='value') # 移除列的层级名称(timestamp) df_pivoted.columns.name = None # 重置索引并将数值列转回整数类型 df_result = df_pivoted.reset_index().astype({col: int for col in df_pivoted.columns})
关键操作说明:
df_pivoted.columns.name = None:清除列上方的timestamp标签,让列名直接显示为1-5astype({col: int for col in df_pivoted.columns}):将重置索引后自动转为浮点数的数值列还原为整数,避免出现.0后缀reset_index():将datecreated从索引列转为普通列,生成默认的整数索引
执行后输出结果与目标格式一致:
datecreated 1 2 3 4 5 0 2022-11-15 4000 3900 3850 3810 3790
内容的提问来源于stack exchange,提问作者Leb_Broth
相关产品推荐
相关产品推荐

