Groupby,旋转并返回熊猫数据框中的所有列

时间:2020-02-05 12:02:31

标签: python python-3.x pandas

我有一只熊猫dataframe,看起来像这样:

    col1    col2    col3    col4    col5    status  count
0   AA      PP      X       Y       13.1764     0   1.0
1   AA      PP      X       Y       12.145      0   1.0
2   AA      PP      X       Y       13.17       0   2.0
3   AA      PP      X       Y       23.5        0   2.0
4   AA      PP      X       Y       1100.4      0   2.0
5   AA      PP      X       Y       20.5        0   3.0
6   AA      PP      X       Y       1300.0      0   3.0
...

我想做什么?

  1. col1分组
  2. 然后按count分组
  3. 展开col5值并附加到其他所有内容

最终数据框应如下所示:

AA         col2 col3 col4 status count1 count2 count3
count  1.0  PP  X    Y     0     13.1764 12.145 NA 
       2.0  PP  X    Y     0     13.17   23.5   1100.4  
       3.0  PP  X    Y     0     20.5    1300.0 NA  

我已经看到很多groupybypivot的问题,相信我,我已经尝试了很多,浪费了一个小时,但无法正确解决问题。

1 个答案:

答案 0 :(得分:0)

如果每个组中所有列的值都与示例数据中的值相同,请使用GroupBy.cumcountpivot_table

// ...
use Authentication\AuthenticationServiceInterface;
use Authentication\AuthenticationServiceProviderInterface;
use Cake\Http\BaseApplication;
use Psr\Http\Message\ServerRequestInterface;

class Application extends BaseApplication implements AuthenticationServiceProviderInterface
{
    // ...

    public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
    {
        // ...
        return $authenticationService;
    }

    public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
    {
        $middlewareQueue
            // ...
            ->add(new RoutingMiddleware($this))
            ->add(new AuthenticationMiddleware($this));

        return $middlewareQueue;
    }

    // ...
}