简体   繁体   English

将新的键和值添加到键匹配的现有字典中

[英]Add new keys and values to an existing dictionary where the keys are matched

I would like to calculate the cost of product c = 20 $ and d = 30$ .我想计算产品c = 20 $d = 30$的成本。 Since I have meta data and df as separated data frame I need to join them somehow where I can then get the price and the number of items bought for each product (eg c:5 ) in a dictionary for each individual id, and then calculated the price of each product (eg for product c 1 * 20 )由于我有meta data和 df 作为单独的数据框,我需要以某种方式加入它们,然后我可以在字典中为每个单独的 id 获取价格和为每个产品购买的商品数量(例如c:5 ),然后计算每个产品的价格(例如产品c 1 * 20

  1. My First data frame我的第一个数据框

    Metadata = {'product_name': ["c", "d"], 'product_price': [20, 30]} Metadata = pd.DataFrame(data=Metadata )
  2. My second data frame我的第二个数据框

    df = pd.DataFrame({'id':[1,2,3], 'product':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})

Edited

  1. My attempts: So I thought I need to get access to the keys and then use them for later for matching.我的尝试:所以我认为我需要访问密钥,然后将它们用于以后进行匹配。 I start with converting the Metadata table into a dictionary:我首先将Metadata表转换为字典:
     def get_product_price_dictionary(Metadata): product_info = Metadata product_price_dict = dict() for d in product_info.to_dict('records'): p_name = d["product_name"] p_price = d["product_price"] product_price_dict[p_name] = p_price return product_price_dict test = get_product_price_dictionary(Metadata) test

Output: Output:

{'c': 20, 'd': 30}

Then I get the keys inside my data frame.然后我在我的数据框中获取密钥。

list_keys = []
df_dic = df['product']
for i in range(len(df_dic)):
    if df_dic.iloc[i] is not None:
        each_dic = df_dic.iloc[i]
    for key, value in each_dic.items():
        list_keys.append(key)
list_keys_uique = list(set(list_keys))
list_keys_uique[0:5]

Output

['c', 'd']

I have recently get started working with python and now, I am really stuck in working with dictionary!我最近开始使用 python 现在,我真的被困在使用字典中了! to get the column called product_cost in the df data frame.在 df 数据框中获取名为product_cost的列。

And now I do not know how to precede with it!!!现在我不知道如何处理它!

I would not turn everything to dict as Pandas is already very fast.我不会将所有内容都转为 dict,因为 Pandas 已经非常快了。 You can search for certain values within a database using double equators together with the row name:您可以使用双等号和行名在数据库中搜索某些值:

df[df['row']==key].value

I added a little piece of code which walks your database and calculates the total money of each transaction:我添加了一小段代码,它遍历您的数据库并计算每笔交易的总金额:

Metadata  = {'product_name': ["c", "d"], 'product_price': [20, 30]}
Metadata = pd.DataFrame(data=Metadata )

df = pd.DataFrame({'id':[1,2,3], 'product':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})

print (Metadata)
print (df)

for action in df['product']:
  print ('action:', action)
  total = 0
  for product in action:
    price = float(Metadata[Metadata['product_name']==product].product_price)
    print ('  product: %s, price: %.2f' % (product, price))
    print ('    count: %i, sum: %.2f' % (action[product], price * action[product]))
    total += price * action[product]
  print ('  total: %.2f' % total)

Console output of the above code:上述代码的控制台output:

  product_name  product_price
0            c             20
1            d             30
   id           product
0   1          {'c': 1}
1   2          {'d': 3}
2   3  {'c': 5, 'd': 6}
action: {'c': 1}
  product: c, price: 20.00
    count: 1, sum: 20.00
  total: 20.00
action: {'d': 3}
  product: d, price: 30.00
    count: 3, sum: 90.00
  total: 90.00
action: {'c': 5, 'd': 6}
  product: c, price: 20.00
    count: 5, sum: 100.00
  product: d, price: 30.00
    count: 6, sum: 180.00
  total: 280.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM