简体   繁体   English

按特定列分组,列出其他列 Pandas

[英]Group by a specific column, list the other columns Pandas

I am trying to group a column in a data frame, and I want the other columns to be added to a list of elements.我正在尝试对数据框中的一列进行分组,并且我希望将其他列添加到元素列表中。

I have a data frame similar to this:我有一个类似的数据框:

Route  Station  Position
A1      X1         P1        
A1      X2         P2        
A1      X3         P3      
B2      Y1         P1   
B2      Y2         P2

The expected output it should look like this:预期的 output 应该如下所示:

Route  Station  Position
A1   [X1,X2,X3] [P1,P2,P3]       
B2    [Y1,Y2]    [P1,P2]   

What is the correct way to do it?正确的方法是什么?

Use:利用:

df.groupby('Route', as_index=False).agg(list)

Output: Output:

  Route       Station      Position
0    A1  [X1, X2, X3]  [P1, P2, P3]
1    B2      [Y1, Y2]      [P1, P2]
>>> m
    R   S   P
0  A1  X1  P1
1  A1  X2  P2
2  A1  X3  P3
3  B2  Y1  P1
4  B2  Y2  P2
>>> m.groupby('R').agg( lambda x: list(x) )
               S             P
R                             
A1  [X1, X2, X3]  [P1, P2, P3]
B2      [Y1, Y2]      [P1, P2]
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM