jean jean - 9 days ago 5
Python Question

Group Python List Elements

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]]


I want to order them according to this rule:

1 --> [0.65, 0.62] <--25, 50
2 --> [0.62, 0.63] <--25, 50
3 --> [0.63, 0.65] <--25, 50


So the expected result is as follows:

Result = [[0.65, 0.62],[0.62, 0.63],[0.63, 0.65]]


How to do it guys?

I tried as follows:

df = pd.DataFrame(my_list,columns=['a','b','c'])
res = df.groupby(['b', 'c']).get_group('c')
print res

ValueError: must supply a tuple to get_group with multiple grouping keys

Answer

You can sort your list with native python, but I find it easiest to get your required list using numpy. Since you were going to use pandas anyway, I consider this to be an acceptable solution:

from operator import itemgetter
import numpy as np
# or just use pandas.np if you have that already imported

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]]

sorted_list = sorted(my_list,key=itemgetter(1,0)) # sort by second and first column
sliced_array = np.array(sorted_list)[:,-1].reshape(-1,2)
final_list = sliced_array.tolist() # to get a list

The main point is to use itemgetter to sort your list on two columns one after the other. The resulting sorted list contains the required elements in its third column, which I extract with numpy. It could be done with native python, but if you're already using numpy/pandas, this should be natural.