python - 将一个数据帧值与一个数据帧列合并

标签 python pandas merge

我这里有一个困难。我的目标是为一家商店创建一份销售列表,其中一个数据框按产品列出价格,另一个数据框则列出按产品和数量列出的所有销售(一段时间内)

DataFrame 1:价格

prices = pd.DataFrame({'qty_from' : ('0','10','20'), 'qty_to' : ('9','19','29'), 'product_A' :(50,30,10),'product_B' :(24,14,12),'product_C' :(70,50,18)})

数据框 2:销售

sales = pd.DataFrame({'product' : ('product_b','product_b','product_a',product_c,product_b), 'qty' : ('4','12','21','41','7')})

我想在“销售”数据框中逐行获取营业额,以及另一列,例如“营业额”

我用过

pd.merge_asof(sales, prices, left_on='qty', right_on='qty_from', direction='backward') 

它为我提供了适合销售数量的正确价格,但如何获得与一种产品相关的好价格? 如何将“sales”数据框中的值(如“product_b”)与数据框价格中的列名称(此处为“product_b”)合并,然后应用计算来获取营业额?

感谢您的帮助,

埃里克

最佳答案

如果我理解正确,您可以修改数据帧价格,以便能够使用 merge_asof 中的参数 by,使用 stack:

#modify price
prices_stack = (prices.set_index(['qty_from','qty_to']).stack() # then products become as a column
                     .reset_index(name='price').rename(columns={'level_2':'product'}))

# uniform the case
sales['product'] = sales['product'].str.lower()
prices_stack['product'] = prices_stack['product'].str.lower()
# this is necessary with your data here as not int
sales.qty = sales.qty.astype(int)
prices_stack.qty_from = prices_stack.qty_from.astype(int)

#now you can merge_asof adding by parameter
sales_prices = (pd.merge_asof( sales.sort_values('qty'), prices_stack, 
                               left_on='qty', right_on='qty_from', 
                               by = 'product', #first merge on the column product
                               direction='backward')
                  .drop(['qty_from','qty_to'], axis=1)) #not necessary columns

print (sales_prices)
     product  qty  price
0  product_b    4     24
1  product_b    7     24
2  product_b   12     14
3  product_a   21     10
4  product_c   41     18

关于python - 将一个数据帧值与一个数据帧列合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54911779/

相关文章:

python - 在 anaconda 中安装 OpenCV 未显示在 Windows 10 的 VS Code 中

python - 避免将 DLL 放入 CWD

Python - BeautifulSoup - HTML 解析

python - 管理 django 请求类型的最佳方法是什么?

python - 使用 Matplotlib 绘制二元高斯分布

svn - Subversion 合并需要 "Old style"即使一切看起来都是最新的?

python - Pandas - 在 DataFrame 中的任何位置查找值索引

python - 对 pandas 日期时间索引进行排序

java - 组合不同arff文件的属性

android - 编译错误说资源名称必须以字母开头