我有一个包含客户所有交易数据的数据框。列是 mailid、txn_date、城市。现在我遇到的情况是,我必须考虑 2016 年 1 月 1 日以来的客户,对于每个 mailid,我必须从基本文件中获取他们的 txn 数据,并考虑他们最近 12 个月的数据(上次 Txn 日期和 -365 天时间增量之间的 txn 日期)然后找出他们的最大交易城市名称。
示例基础数据框
#df
maild txn_date city
satya 2015-07-21 a
satya 2015-08-11 b
satya 2016-05-11 c
xyz 2016-06-01 f
satya 2016-06-01 a
satya 2016-06-01 b
因为我需要 2016-01-01 的客户所以我这样做了
d = df[['mailid', 'txn-date']][df['txn_date'] >= '2016-01-01']
现在,对于 d 中的每个电子邮件 ID,我必须从基本 Dataframe df 中获取他们最近 12 个月的交易数据,并计算他们的最大交易城市。为此,我使用 for 循环,例如
x = d.groupby(['mailid'])['txn-date'].max().reset_index() #### finding their last transacted date to find out a 12 Month back date
x['max_city'] = 'N' ## giving default value as 'N'
for idx,row in x.iterrows():
g = row[1].date()
h = g-timedelta(days=365) ###getting the last 12 Month date
y = df[(df['mailid']==row[0]) & (df['txn_date'] >= str(h))]
y.sort(['txn_date'],ascending=True,inplace=True) ### sorting it bcoz i want to consider the last txn when count for one or more cities become same
c = y.groupby(['mailid','city']).size().reset_index()
v = c.groupby(['mailid'])[0].max().reset_index()
dca = pd.merge(y,c,on=['mailid','city'],how='left')
dcb = pd.merge(dca,v,on=['mailid',0])
m = dcb.drop_duplicates(['mailid'],take_last=True)
row[2] = m['city'].unique()[0]
o/p:
maild max_city
satya b ### as in last 12 month 2016-06-01 2015-06-01 txn in a=2 b= 2 so last is b so will consider b as max city
xyz f
尽管我的代码对于小块数据有效(我确信它是无组织的,并且在我练习时没有使用正确的命名约定),并且循环将命中数据帧 x 中存在的每个客户的主基本数据帧 df 。
所以我主要关心的是我的 df 是否为 100Mln rows 而 x 是否为 6mln Rows 。然后 for 循环将执行 600 万次,并会命中 df 来获取匹配的 mailid 数据并执行操作以查找最大交易城市。
如果在 1 分钟内它将计算 3 个 mailid 的最大城市。那么对于 600 万,将需要 200 万分钟......这将是一个严重的问题......
因此,需要你们提出如何优化场景的建议……从而减少主基地的次数,并应用一些更方便的 PANDAS 方法来实现这一点(我还无法做到)……
请建议!!!提前致谢。