Skip to main content
 首页 » 编程设计

python之合并数据帧中的 MUL 操作

2024年12月31日11dudu

数据 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') 

数据2

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) 

请您参考如下方法:

如果我没理解错的话,要在数据框中定义一个新列,请使用:

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