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

如何在Python中将DataFrame行转列?混合类型数据处理需求

解决方案

你需要将inv列的唯一值转为新列,以store和period作为复合索引,对应填充info的混合类型值。以下是两种可行方法:

方法1:使用pivot函数

当store+period+inv的组合无重复时,pivot是最直接的方案,它能直接完成行列转换并保留原始值类型:

result = df.pivot(index=['store', 'period'], columns='inv', values='info').reset_index()

方法2:使用pivot_table函数

如果数据存在少量重复的store+period+inv组合,可指定aggfunc='first'保留第一个出现的值,同样支持混合类型:

result = df.pivot_table(index=['store', 'period'], columns='inv', values='info', aggfunc='first').reset_index()

完整验证代码

import pandas as pd

inv = ['Z15','Z15','Z15','Z15','Z15','Z15','Z15','Z15','Z15','Z17','Z17','Z17','Z17','Z17','Z17','Z17']
store = ['store1','store1','store1','store2','store2','store2','store2','store2','store2','store3','store4','store5','store6','store7','store1','store2']
period = [2018,2019,2020,2015,2016,2017,2018,2019,2020,2022,2022,2022,2022,2022,2018,2019]
info = ['0.84773','0.8487','0.82254','0.75','0.65','0.432','0.546','0.777','0.1','High','High','Medium','Very Low','Low','High','Low']

df = pd.DataFrame({'inv':inv,
                'store':store,
                'period':period,
                'info':info})

# 执行转换
result = df.pivot(index=['store', 'period'], columns='inv', values='info').reset_index()
print(result)

输出结果

inv    store  period    Z15      Z17
0     store1    2018  0.84773    High
1     store1    2019  0.8487     NaN
2     store1    2020  0.82254    NaN
3     store2    2015  0.75       NaN
4     store2    2016  0.65       NaN
5     store2    2017  0.432      NaN
6     store2    2018  0.546      NaN
7     store2    2019  0.777      Low
8     store2    2020  0.1        NaN
9     store3    2022  NaN        High
10    store4    2022  NaN        High
11    store5    2022  NaN        Medium
12    store6    2022  NaN        Very Low
13    store7    2022  NaN        Low

注意事项

  • 针对你的大规模数据集(100+门店、400+库存项、30+周期),这两种方法的效率都能满足需求;
  • 结果中的NaN表示对应门店-周期组合无该库存项的info值,可通过fillna()按需填充;
  • 若存在重复组合,可根据业务需求替换aggfunc,比如'last'或自定义处理函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:11:39