合并数据帧中的MUL操作

时间:2018-07-03 18:17:46

标签: python python-3.x pandas

数据1

import pandas as pd
#data 01
df_products = pd.DataFrame([{'Product ID' : 4109,'Price' : 5.0,'Product' : 'Sushi Roll'},
                   {'Product ID' : 1412,'Price' : 0.5,'Product' : 'Egg'},
                   {'Product ID' : 8931,'Price' : 1.5,'Product' : 'Bagel'}])
df_products = df_products.set_index('Product ID')

data2

df_invoices = pd.DataFrame([{'Customer' : 'Ali' , 'Product ID' : 4109 , 'Quantity' : 1},
                        {'Customer' : 'Eric' , 'Product ID' : 1412 , 'Quantity' : 12},
                        {'Customer' : 'Ande' , 'Product ID' : 8931 , 'Quantity' : 6},
                        {'Customer' : 'Sam' , 'Product ID' : 4109 , 'Quantity' : 2}])

df_invoices = df_invoices.set_index('Product ID')

合并数据

df_overall = pd.merge(df_products , df_invoices , how='outer' , left_index = 
True ,right_index = True)

已支付总金额的新数据框

df_total = df_overall['Price'] * df_overall['Quantity']

我想显示所有带有结果的数据框!

但是最后一行不能正常工作!

    df_result = pd.merge(df_overall , df_total , how='outer' ,
left_index = True , right_index = True)

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,请在数据框中定义新列,使用:

df_overall['Total'] = df_overall['Price'] * df_overall['Quantity']

print(df_overall)

输出:

            Price     Product Customer  Quantity  Total
Product ID                                             
1412          0.5         Egg     Eric        12    6.0
4109          5.0  Sushi Roll      Ali         1    5.0
4109          5.0  Sushi Roll      Sam         2   10.0
8931          1.5       Bagel     Ande         6    9.0