Group Python List Elements

后端 未结 4 1877
误落风尘
误落风尘 2021-01-29 10:49

I have a python list as follows:

my_list = 

 [[25, 1, 0.65],
 [25, 3, 0.63],
 [25, 2, 0.62],
 [50, 3, 0.65],
 [50, 2, 0.63], 
 [50, 1, 0.62]]

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 11:35

    A way to do this with pandas is to extract each group, pull out 'c', convert to a list and append to the list you want :

    z = []
    >>> for g in df.groupby('b'):
            z.append(g[1]['c'].tolist())
    
    >>> z
    [[0.65, 0.62], [0.62, 0.63], [0.63, 0.65]]
    

    You could do this as a list comprehension:

    >>> res = [g[1]['c'].tolist() for g in df.groupby('b')]
    
    >>> res
    [[0.65, 0.62], [0.62, 0.63], [0.63, 0.65]]
    

    Another way would be to apply list directly to df.groupby('b')['c'] this gives you the object you need. Then call the .tolist() method to return a list of lists:

    >>> df.groupby('b')['c'].apply(list).tolist()
    [[0.65000000000000002, 0.62], [0.62, 0.63], [0.63, 0.65000000000000002]] 
    

提交回复
热议问题