【发布时间】:2019-12-02 13:20:41
【问题描述】:
我有两个与销售分析相关的不同数据框。我想将它们合并在一起以创建一个新的数据框,其中包含 customer_id、name 和 total_spend 列。两个数据框如下:
import pandas as pd
import numpy as np
customers = pd.DataFrame([[100, 'Prometheus Barwis', 'prometheus.barwis@me.com',
'(533) 072-2779'],[101, 'Alain Hennesey', 'alain.hennesey@facebook.com',
'(942) 208-8460'],[102, 'Chao Peachy', 'chao.peachy@me.com',
'(510) 121-0098'],[103, 'Somtochukwu Mouritsen',
'somtochukwu.mouritsen@me.com','(669) 504-8080'],[104,
'Elisabeth Berry', 'elisabeth.berry@facebook.com','(802) 973-8267']],
columns = ['customer_id', 'name', 'email', 'phone'])
orders = pd.DataFrame([[1000, 100, 144.82], [1001, 100, 140.93],
[1002, 102, 104.26], [1003, 100, 194.6 ], [1004, 100, 307.72],
[1005, 101, 36.69], [1006, 104, 39.59], [1007, 104, 430.94],
[1008, 103, 31.4 ], [1009, 104, 180.69], [1010, 102, 383.35],
[1011, 101, 256.2 ], [1012, 103, 930.56], [1013, 100, 423.77],
[1014, 101, 309.53], [1015, 102, 299.19]],
columns = ['order_id', 'customer_id', 'order_total'])
当我按 customer_id 和 order_id 分组时,我得到下表:
customer_id order_id order_total
100 1000 144.82
1001 140.93
1003 194.60
1004 307.72
1013 423.77
101 1005 36.69
1011 256.20
1014 309.53
102 1002 104.26
1010 383.35
1015 299.19
103 1008 31.40
1012 930.56
104 1006 39.59
1007 430.94
1009 180.69
这就是我卡住的地方。我不知道如何汇总每个 customer_id 的所有订单以创建一个 total_spent 列。如果有人知道这样做的方法,将不胜感激!
【问题讨论】:
-
您的分组似乎超出了必要的级别 - 您是如何做到的?你最终追求的是什么?是不是类似于:
customers['total_spend'] = customers['customer_id'].map(orders.groupby('customer_id')['order_total'].sum())? -
我通过
customer_spend = pd.merge(customers, orders) customer_spend.groupby(["customer_id", 'order_id']).sum()得到了上面的表格 最终我想要一张决赛桌,它会给我 customer_id、姓名以及那个人一起花了多少钱(因此新的 total_spend 列) -
上面不是这样吗?
-
你的问题和答案已找到here
-
您的预期输出是什么?
标签: python-3.x pandas numpy dataframe