[英]how to calculate percentage with nested dictionary
I'm stuck with how to calculate percentages with nested dictionary.我不知道如何使用嵌套字典计算百分比。 I have a dictionay
defined by old_dict = {'X': {'a': 0.69, 'b': 0.31}, 'Y': {'a': 0.96, 'c': 0.04}}
, and I know the percentage of X
and Y
are in the table:我有一个由dictionay
old_dict = {'X': {'a': 0.69, 'b': 0.31}, 'Y': {'a': 0.96, 'c': 0.04}}
定义的字典,我知道X
和Y
的百分比在表中:
input= {"name":['X','Y'],"percentage":[0.9,0.1]}
table = pd.DataFrame(input)
OUTPUT:
name percentage
0 X 0.9
1 Y 0.1
But I hope to use the percentage of X and Y to multiply by a,b, c separately.但我希望用X和Y的百分比分别乘以a,b,c。 That is, X*a = 0.9*0.69
, X*b = 0.9*0.31
, Y*a = 0.1*0.96
, Y*c = 0.1*0.04
... so that I can find the mixed percentage of a, b, and c, and finally got a new dictionary new_dict = {'a': 0.717, 'b': 0.279,'c': 0.004}
.即X*a = 0.9*0.69
, X*b = 0.9*0.31
, Y*a = 0.1*0.96
, Y*c = 0.1*0.04
... 这样我就可以找到 a, b 的混合百分比,和 c,最后得到一个新字典new_dict = {'a': 0.717, 'b': 0.279,'c': 0.004}
。
I'm struggling with how to break through the nested dictionary and how to link X and Y with the corresponding value in the table.我正在努力解决如何突破嵌套字典以及如何将 X 和 Y 与表中的相应值联系起来。 Can anyone help me?谁能帮我? Thank you!谢谢!
You could use a DataFrame for the first dictionary and a Series for the second and perform an aligned multiplication, then sum
:您可以将 DataFrame 用于第一个字典,将 Series 用于第二个字典并执行对齐乘法,然后sum
:
old_dict = {'X': {'a': 0.69, 'b': 0.31}, 'Y': {'a': 0.96, 'c': 0.04}}
df = pd.DataFrame(old_dict)
inpt = {"name":['X','Y'],"percentage":[0.9,0.1]}
table = pd.DataFrame(inpt)
# convert table to series:
ser = table.set_index('name')['percentage']
# alternative build directly a Series:
# ser = pd.Series(dict(zip(*inpt.values())))
# compute expected values:
out = (df*ser).sum(axis=1).to_dict()
output: {'a': 0.717, 'b': 0.279, 'c': 0.004}
output: {'a': 0.717, 'b': 0.279, 'c': 0.004}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.