I have a list of lists looking like this:
['user1', time, cpus, mem]
['user1', time, cpus, mem]
['user2', time, cpus, mem]
['user3', time, cpus, mem]
and so on..
I need just one list per user with time, cpus and mem added together. I've tried a few things but i cant make it work.
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.
We can have a list of many types in Python, like strings, numbers, and more. Python also allows us to have a list within a list called a nested list or a two-dimensional list.
You can concatenate multiple lists into one list by using the * operator. For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object. Usecase: You can use this method when you want to concatenate multiple lists into a single list in one shot.
A sweet, Pythonic and concise way to do that would be:
from collections import defaultdict
l = [
['user1', 0, 1, 0],
['user2', 2, 2, 2],
['user3', 2, 2, 1],
['user3', 1, 1, 2],
['user1', 1, 0, 1],
]
merged = defaultdict(lambda: [0, 0, 0])
for user, *values in l:
merged[user] = [sum(i) for i in zip(values, merged[user])]
Output:
In : merged
Out:
defaultdict(<function __main__.<lambda>>,
{'user1': [1, 1, 1], 'user2': [2, 2, 2], 'user3': [3, 3, 3]})
That uses a defaultdict
with a list
of length 3 as its default value. The relevant user's values are updated for each element in the list.
You can do this using a dictionary
in order to group list items by user
.
Then just use zip
function to find out the sum for every feature from time, cpus, mem
list.
mylist = [['user1', 1, 6, 8],
['user1', 2, 7, 9],
['user2', 3, 7, 5],
['user3', 4, 7, 3]]
dict = {}
for elem in mylist:
if elem[0] not in dict:
dict[elem[0]] = []
dict[elem[0]].append(elem[1:])
for key in dict:
dict[key] = [sum(i) for i in zip(*dict[key])]
Output
In[1]: dict
Out[1]: {'user1': [3, 13, 17], 'user2': [3, 7, 5], 'user3': [4, 7, 3]}
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