熊猫在不同数据框中使用相等的单元格值应用折扣

时间:2018-10-31 03:10:37

标签: python pandas numpy

我很绝望。我现在已经解决了3天了。我确实在类似的帖子中尝试了所有解决方案。我的解决方案适用于其他数据框,但无法解决这一问题。 我有两个数据集:一个包含项目,常规价格和折扣组列。第二个-折扣组和该组的折扣。 我需要带物品,获得折扣组,查找折扣并将其乘以价格。但是在某些行中我得到了错误。这是我的代码:

for index, row in df1.iterrows():

   discount_group = df1['Discount group'][index]
   #this returns data frame with discount group and relevant discount
   discounts_df = df2.loc[df2['Discount group'] == discount_group], 'Discount'
   discount = discounts_df[0].values[0][1]
   row ['Discounted price'] = row['Price'] * discount

但是在某些情况下,discounts_df = df2.loc[df2['Discount group'] == discount_group], 'Discount'返回空的数据帧。我确实将折扣组列转换为浮点数,以确保与df1['RG'] = df1['Discount group'].astype(float)没有类型不匹配。它没有帮助。

也许还有其他解决方案?

感谢帮助!

1 个答案:

答案 0 :(得分:0)

我认为,使用.merge().iterrows()更好。 .merge()允许数据库样式的连接,请参见documentation。这是一个玩具示例,该示例对价格列应用百分比折扣(0到1之间)。

import pandas as pd
import numpy as np

facts = pd.DataFrame(
    {
        'price': np.random.randn(10),
        'discount_id': np.tile([1, 2], 5)
    }
)

discount = pd.DataFrame(
    {
        'discount_id': [1, 2],
        'discount_value': [.5, .1]
    }
)

merged = facts.merge(discount, on = 'discount_id')

# Adapt this line to apply your specific discounting logic.

merged['discounted_price'] = merged['price'] - (merged['price'] * merged['discount_value'])

print(merged)

礼物:

      price  discount_id  discount_value  discounted_price
0 -0.186169            1             0.5         -0.093084
1 -1.345143            1             0.5         -0.672572
2 -0.044090            1             0.5         -0.022045
3  0.325579            1             0.5          0.162790
4  0.794152            1             0.5          0.397076
5  1.271465            2             0.1          1.144318
6  1.041492            2             0.1          0.937342
7 -0.774214            2             0.1         -0.696793
8  0.917996            2             0.1          0.826196
9  1.055927            2             0.1          0.950334