Hello this is using python panda
JavaScript
x
7
1
from collections import defaultdict
2
Unknown_dict = defaultdict(list)
3
for j, k in zip(my_unknown_id, my_unknown_intensity):
4
Unknown_dict[j].append(k)
5
6
print(Unknown_dict)
7
From the above code what I get is
JavaScript
1
2
1
defaultdict(<class 'list'>, {'ABC': [123, 345, 678], 'JIK': [456, 789], 'KIL': [100], 'JAL': [200], 'HON': [300]})
2
From this list I want to actually get the mean of the values inside the class list. For example for ABC I want to get (123+345+678)/3 and for JIK (456+789)/2.
I tried getting the mean of the values but I found out inside lists we cannot change values. I’m not sure if I got it wrong or does anyone know how to get the mean inside a list?
Advertisement
Answer
You can get the mean with a comprehension –
JavaScript
1
4
1
d = defaultdict(list, {'ABC': [123, 345, 678], 'JIK': [456, 789], 'KIL': [100], 'JAL': [200], 'HON': [300]})
2
mean_d = {k: sum(v) / len(v) for k, v in d.items()}
3
# {'ABC': 382.0, 'JIK': 622.5, 'KIL': 100.0, 'JAL': 200.0, 'HON': 300.0}
4
If you want to add these mean values back into the original dict –
JavaScript
1
3
1
for k in mean_d:
2
d[k].append(mean_d[k])
3
Output
JavaScript
1
7
1
defaultdict(list,
2
{'ABC': [123, 345, 678, 382.0],
3
'JIK': [456, 789, 622.5],
4
'KIL': [100, 100.0],
5
'JAL': [200, 200.0],
6
'HON': [300, 300.0]})
7