代码之家  ›  专栏  ›  技术社区  ›  Bernando Purba

在python数据帧中将特定列转换为行

  •  1
  • Bernando Purba  · 技术社区  · 6 年前

    我尝试将数据帧转换为特定格式: 这是我当前的数据帧,叫做df: enter image description here

    换位的结果应该是: enter image description here

    事先谢谢。

    2 回复  |  直到 6 年前
        1
  •  2
  •   BENY    6 年前

    假设您有以下数据帧,使用 unstack

    df=pd.DataFrame({'pid':[1,1,1],'TreeFeature':['a','b','c'],'Import':[1,2,3],'acc':[1,1,1]})
    df.set_index(['pid','acc','TreeFeature']).Import.unstack().reset_index()
    Out[298]: 
    TreeFeature  pid  acc  a  b  c
    0              1    1  1  2  3
    
        2
  •  1
  •   jpp    6 年前

    您可以尝试使用 pd.pivot_table :

    res = df.pivot_table(index=['pid', 'Accuracy'], columns=['TreeFeatures'],
                         values='Importance 1', aggfunc='first', fill_value=0)
    

    如果需要将索引提升到列,请通过重置索引 res.reset_index() .