如何在Pandas中实现类似Spotfire的透视:拼接列生成新列并保留原列
解决Pandas透视时保留标识列并自定义列名的问题
问题分析
你当前的pivot代码仅将x、y设为索引,导致lot_id、run、wafer这些唯一标识列丢失。要实现Spotfire的透视效果,需要:
- 将所有需保留的标识列纳入透视索引
- 把
test_number与test_name拼接成新的列名
实现步骤
- 创建拼接列:先把
test_number转为字符串,再和test_name拼接成新列(格式如"11.Test2")
fromCSV['test_col'] = fromCSV['test_number'].astype(str) + '.' + fromCSV['test_name']
- 执行透视并还原索引列:将
lot_id、run、wafer、x、y全部设为透视索引,用拼接后的test_col作为列名,最后通过reset_index()把索引转回普通列
pivoted_df = fromCSV.pivot( index=['lot_id', 'run', 'wafer', 'x', 'y'], columns='test_col', values='value' ).reset_index()
结果说明
执行后得到的pivoted_df会以lot_id、run、wafer、x、y作为首列,后续列名均为test_number.test_name的格式,对应位置填充原value值,完全匹配你需要的目标结构。
内容的提问来源于stack exchange,提问作者user21950121
相关产品推荐
相关产品推荐

