从带有刻度的价目表中查找价格

Find the price from a pricelist with scales

在 python 中,我试图根据比例价格列表中的数量查找相关价格。例如,当收到报价请求时:

  Product  Qty  Price
0       A    6
1       B  301
2       C    1
3       D  200
4       E   48

价格表:

   Product  Scale Qty  Scale Price
0        A          1           48
1        A          5           43
2        A         50           38
3        B          1           10
4        B         10            9
5        B         50            7
6        B        100            5
7        B        150            2
8        C          1          300
9        C          2          250
10       C          3          200
11       D          1            5
12       D        100            3
13       D        200            1
14       E          1          100
15       E         10           10
16       E        100            1

我想要的输出:

  Product  Qty  Price
0       A    6     43
1       B  301      2
2       C    1    300
3       D  200      1
4       E   48     10

试试 merge_asof:

output = (pd.merge_asof(df2.sort_values("Qty"),df1.sort_values("Scale Qty"),left_on="Qty",right_on="Scale Qty",by="Product")
          .sort_values("Product", ignore_index=True)
          .drop("Scale Qty", axis=1)
          .rename(columns={"Scale Price":"Price"}))

>>> output
  Product  Qty  Price
0       A    6     43
1       B  301      2
2       C    1    300
3       D  200      1
4       E   48     10
输入:
df1 = pd.DataFrame({'Product': ['A','A','A','B','B','B','B','B','C','C','C','D','D','D','E','E','E'],
                   'Scale Qty': [1, 5, 50, 1, 10, 50, 100, 150, 1, 2, 3, 1, 100, 200, 1, 10, 100],
                   'Scale Price': [48, 43, 38, 10, 9, 7, 5, 2, 300, 250, 200, 5, 3, 1, 100, 10, 1]})

df2 = pd.DataFrame({"Product": list("ABCDE"),
                    "Qty": [6,301,1,200,48]})

假设 df1df2,使用 merge_asof:

pd.merge_asof(df1.sort_values(by='Qty'),
              df2.sort_values(by='Scale Qty').rename(columns={'Scale Price': 'Price'}),
              by='Product', left_on='Qty', right_on='Scale Qty')

输出:

  Product  Qty  Scale Qty  Price
0       C    1          1    300
1       A    6          5     43
2       E   48         10     10
3       D  200        200      1
4       B  301        150      2