[英]How can I sum column values that corrispond to a specific value of another column in a pandas DataFrame?
[英]How can I sum the values in one column based on the floor'd value of another column in pandas?
我有一些具有各種不同價位的銷售數據(如下所示)。 在許多情況下,這些商品將以非常相似的價格出售,例如79.98和79.99。 我想做的是將所有存在於同一美元金額(即最低限度)內的商品的訪問和銷售總和,並且還保留原始價格,因為我將需要以此為基礎來進行加入后來。 例如,使用下面顯示的數據:
product price visits sales conversion
29 12345678 74.98 225 14 0.0622
30 12345678 79.98 302 12 0.0397
31 12345678 79.99 446 19 0.0426
32 12345678 81.98 17 1 0.0588
33 12345678 84.98 11 0 0.0000
34 12345678 84.99 845 52 0.0615
35 12345678 88.98 96 8 0.0833
36 12345678 88.99 81 0 0.0000
37 12345678 89.99 324 13 0.0401
38 12345678 92.98 234 2 0.0085
39 12345678 93.98 97 0 0.0000
40 12345678 94.98 5 0 0.0000
41 12345678 99.99 1069 11 0.0103
產品,selling_price,下限(selling_price),總和(訪問),總和(銷售)
product, selling_price, floored_price, total_visits, total_sales
12345678, 79.98, 79.00, 527, 26
12345678, 79.99, 79.99, 527, 26
最后一部分是我想對熊貓做這件事,原因是我沒有太多控制權。 有任何想法嗎?
如果我正確理解:
pd.merge_asof(df, \
df.assign(floored_price=df.price.apply(np.floor)). \
groupby('floored_price')[['sales', 'visits']].sum(). \
rename(columns={'sales':'total_sales', 'visits':'total_visits'}). \
reset_index(), \
left_on='price', right_on='floored_price')
# product price visits sales conversion floored_price total_sales total_visits
# 0 12345678 74.98 225 14 0.0622 74.0 14 225
# 1 12345678 79.98 302 12 0.0397 79.0 31 748
# 2 12345678 79.99 446 19 0.0426 79.0 31 748
# 3 12345678 81.98 17 1 0.0588 81.0 1 17
# 4 12345678 84.98 11 0 0.0000 84.0 52 856
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.