【问题标题】:calculate price across dataframes for different price types - Python跨数据框计算不同价格类型的价格 - Python
【发布时间】:2020-03-21 15:58:37
【问题描述】:

对于我正在做的一个项目,我目前有 3 个数据框。这些是针对产品、客户和订单的。可以在下面找到这些的简单版本,实际的订单框架大约有 10.000 列。情况如下:产品有不同的价格类别,每个客户对每个类别都有一个特价。我目前有一个订单数据框,其中包含订单客户、产品编号、订购产品的数量和日期。

我现在想在订单数据框中的新列中添加订单价格。我设法在那里获得了产品的类别,但我不知道如何从那里开始,或者是否是正确的方法。任何帮助将不胜感激,在数据帧图片下方,我包含了制作这些示例数据帧的代码。

df_products:

df_customers:

df_orders:

创建数据框的代码:

import pandas as pd 

df_products = pd.DataFrame({'product_number': [1, 2, 3], 'product': ['product 1', 'product 2', 'product 3' ], 'price_type': ['X', 'Y', 'Z']})

df_customers = pd.DataFrame({'customer_number': [1, 2, 3], 'customer': ['customer 1', 'customer 2', 'customer 3' ], 'price_x': [7.50, 10.50, 12.50], 'price_y': [6.50, 9.20, 11.30], 'price_z': [8.50, 10.10, 13.40]})

df_orders = pd.DataFrame({'order_number': [1, 2, 3], 'date': ['19-03-2020', '19-03-2020', '20-03-2020' ], 'customer_number': [1, 3, 2], 'product_number': [1, 2, 3], 'amount': [1, 2, 2]})

提前致谢:)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    如果数据框的长度相同,您只需添加一个新列即可。下面我向 df_orders 添加一个新列 'price' 并使用来自 df_customers['price_y'] 的值填充它。

    这样,

    df_orders['price']=df_customers['price_y']
    

    结果是,

    df_orders.head()
    
    
    
    order_number    date    customer_number     product_number  amount  price
    0   1   19-03-2020  1   1   1   6.5
    1   2   19-03-2020  3   2   2   9.2
    2   3   20-03-2020  2   3   2   11.3
    

    【讨论】:

    • 它们的长度不同,但这也不起作用,因为并非所有产品都有价格类型 Y
    • 我以 price_y 为例,因为您没有在订单数据框中指定您想要的价格。我看到客户和订单有不同的列,客户列是不同的。试试 pd.melt
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多