Dictionary Comprehension to get Sum of Dictionary Values based on keys in a column of dataframe

69 Views Asked by At

I have a dictionary as

Er = {'A':3,'B':5,'C':7,'D':6}

and a dataframe as

df = pd.DataFrame({'r': ['A', 'B', 'D', ]})

how do i get total of dictionary values with dictionary comprehension where, keys are matching in dataframe column? something like for A,B and D in dataframe, sum of corresponding values in dictionary is 3+5+6 = 14.

1

There are 1 best solutions below

0
inquirer On

It seems easier to me to turn the dictionary into a dataframe.

import pandas as pd

df1 = pd.DataFrame([Er])

print(df1)

Output

   A  B  C  D
0  3  5  7  6

Into a dataframe and serve df rows as indexes.

print(df1[df['r']].sum(axis=1))

Output

0    14
dtype: int64