Group Python List Elements

后端 未结 4 1874
误落风尘
误落风尘 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:25

    The numpy_indexed package (disclaimer: I am its author) has a one-liner for these kind of problems:

    import numpy_indexed as npi
    my_list = np.asarray(my_list)
    keys, table = npi.Table(my_list[:, 1], my_list[:, 0]).mean(my_list[:, 2])
    

    Note that if duplicate values are present in the list, the mean is reported in the table.

    EDIT: added some improvements to the master of numpy_indexed, that allow more control over the way you convert to a table; for instance, there is Table.unique which asserts that each item in the table occurs once in the list, and Table.sum; and eventually all other reductions supported by the numpy_indexed package that make sense. Hopefully I can do a new release for that tonight.

提交回复
热议问题