Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 熊猫从长到宽模式旋转,重复_Python 3.x_Pandas_Pivot_Pivot Table - Fatal编程技术网

Python 3.x 熊猫从长到宽模式旋转,重复

Python 3.x 熊猫从长到宽模式旋转,重复,python-3.x,pandas,pivot,pivot-table,Python 3.x,Pandas,Pivot,Pivot Table,我有一个属性名在col1中,属性值在col2中。我想: 将col1中的所有唯一行透视到df中的列 将col2中的相应值指定给行 pivot不工作,因为存在重复的值 pivot_table不起作用,因为aggfunc只返回means等,而我需要对所有行进行数据透视 我没有成功使用melt或unstack 原始df: col1 col2 attr1 2 attr2 6 attr3 3 ... ... attr1 9 attr2 2 attr3 5 期望输出:

我有一个属性名在col1中,属性值在col2中。我想:

  • 将col1中的所有唯一行透视到df中的列
  • 将col2中的相应值指定给行
  • pivot
    不工作,因为存在重复的值

    pivot_table
    不起作用,因为
    aggfunc
    只返回means等,而我需要对所有行进行数据透视

    我没有成功使用
    melt
    unstack

    原始df:

    col1    col2
    attr1   2
    attr2   6
    attr3   3
    ...     ...
    attr1   9
    attr2   2
    attr3   5
    
    期望输出:

    attr1    attr2    attr3
    2        6        3
    9        2        5 
    

    使用
    set\u index
    groupby
    cumcount
    unstack

    df.set_index([df.groupby('col1').cumcount(),'col1'])['col2'].unstack()
    
    输出:

    col1 attr1 attr2 attr3
    0        2     6     3
    1        9     2     5
    

    没有一个可复制的例子,很难帮助。。。但是,您是否尝试过使用
    .T
    ?--不,那不管用,管用!我很惊讶这种行为不是pivot所固有的。
    pivot
    @akr24若要使用pivot,您仍然需要创建helper列,以了解如何定义像df.assign(row=df.groupby('col1').cumcount()).pivot('row','col1')很好的解决方案,@ScottBoston!不过,有一个简单的问题:在这之后我们如何恢复索引?@mairan我不确定您要恢复什么索引。您是否可以开始一个新的问题,显示您的输入数据帧,并使用所需的索引输出。