Sum Values Of Dynamically Created Dictionaries Using Counter From Collections
I have this df: import pandas as pd a = [1,1,1,2,2,3,3,3,3,4,4,5,5,5] b = ['pi','pi','k','J','pi','pi','k','k','J','pi','k','pi','k','pi'] bin0 = [0,0,0,1,0,0,1,0,0,0,1,1,0,0] bin1
Solution 1:
Isn't it this what you want to achieve:
df_test.groupby(['a', 'b']).sum().reset_index().groupby('a').sum()
bin0 bin1 bin2
a
1 0 3 0
2 1 1 0
3 1 2 1
4 1 0 1
5 1 1 1
Solution 2:
You're going a lot of crazy things here I think are probably unnecessary and I'd really advise against (eval
, setattr
), but to answer just your question about summing the values of two counters with shared keys:
from collections import Counter
cx = Counter(x)
cy = Counter(y)
totals = {k:cx.get(k,0) + cy.get(k,0) for k in (set(cx) | set(cy))}
print(totals)
You take the union of both dictionary keys, iterate over it, and use the Counter.get(key, default)
method to get the value of the associated key and provide a fallback default if it doesn't exist.
This is a dictionary comprehension but you could also do:
for k in (set(cx) | set(cy)):
total = cx.get(k,0) + cy.get(k,0)
print(k, total)
For example, using data built with:
from random import choice
x = [choice("abcdefg") for _ in range(100)]
y = [choice("abcdefg") for _ in range(100)]
y.extend(["z"] * 3)
Solution 3:
Try to use update() method of dict https://www.tutorialspoint.com/python/dictionary_update.htm
count.update(other[elem])
Post a Comment for "Sum Values Of Dynamically Created Dictionaries Using Counter From Collections"