Let's say I have a list like this:
mylist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
How can I most elegantly group this to get this list output in Python:
[["A", "C"], ["B"], ["D", "E"]]
So the values are grouped by the secound value but the order is preserved...
You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.
The groupby method will return a list of the tuples with the element and its group. In every iteration, convert the group of similar elements into a list. Append the list to the empty list. Print the result.
The count() is a built-in function in Python. It will return you the count of a given element in a list or a string. In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.
To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.
values = set(map(lambda x:x[1], mylist)) newlist = [[y[0] for y in mylist if y[1]==x] for x in values]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With