简体   繁体   English

根据另一个数据框中的值将列添加到数据框中

[英]Adding column to dataframe based on values in another dataframe

I have two dataframes the first one:我有两个数据框第一个:

df1 : df1

   product     price
0  apples      1.99
1  bananas     1.20 
2  oranges     1.49
3  lemons      0.5
4  Olive Oil   8.99

df2: df2:

   product     product.1     product.2 
0  apples      bananas       Olive Oil
1  bananas     lemons        oranges
2  Olive Oil   bananas       oranges
3  lemons      apples        bananas

I want a column in the second dataframe to be the sum of the prices base on the price of each item in the first dataframe.我希望第二个数据框中的一列是基于第一个数据框中每个项目的价格的价格总和。 So desired outcome would be:所以想要的结果是:

   product     product.1     product.2     total_price 
0  apples      bananas       Olive Oil     12.18
1  bananas     lemons        oranges       3.19
2  Olive Oil   bananas       oranges       11.68
3  lemons      apples        bananas       3.69

What is the best way to accomplish this?实现这一目标的最佳方法是什么? I have tried merging the dataframes on the name for each of the columns in df2 but this seems time consuming especially as df1 gets more rows and df2 gets more columns.我曾尝试合并 df2 中每一列的名称上的数据帧,但这似乎很耗时,尤其是当 df1 获得更多行而 df2 获得更多列时。

df = pd.merge(df1, df2, how='right', left_on='product', right_on='product')
df = pd.merge(df1, df2, how='right', left_on='product', right_on='product.1')
df = pd.merge(df1, df2, how='right', left_on='product', right_on='product.2') 
df['Total_Price'] = df['price']+df['price.1']+df['price.2']

You can try something like below:您可以尝试以下操作:

  1. First, converting df1 to dictionary of keys and values首先,将 df1 转换为键值字典
  2. Using dictionary in above with applymap followed by sum使用上面的字典与applymap后跟sum

May be following snippet will do something similar:可能以下代码段会做类似的事情:

dictionary_val = { k[0]: k[1] for k in df1.values }
df2['Total_Price'] = df2.applymap(lambda row: dictionary_val[row]).sum(axis=1) # Note not creating new dataframe but using existing one

Then result is df2 :然后结果是df2

    product    product.1    product.2   Total_Price
0   apples      bananas     Olive Oil    12.18
1   bananas     lemons      oranges      3.19
2   Olive Oil   bananas     oranges      11.68
3   lemons      apples      bananas      3.69

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

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