在groupby之后,在pandas中的时间段之间获取列的唯一值



我有一个要求,我需要在特定时间段内,在同一张stampcard上找到用户的merchant_store_id的所有唯一值。我按照stampcard id和userid进行了分组,以获得基于条件的数据帧。现在,我需要找到这个数据帧的唯一merchant_store_id,从该条目开始间隔10分钟。

我的方法是,我会按数据帧在该组中循环,然后找到该组数据帧中的所有索引,然后从索引到索引+60分钟创建一个新的数据帧,然后在其中找到唯一的merchant_store_id。如果唯一的merhant_store_id>1,我会将该时间的数据帧附加到最终的数据帧中。这种方法的问题是,它对小数据很有效,但对于20000行大小的数据,它在linux上显示内存错误,并在windows上继续运行。下面是我的代码

fi_df = pd.DataFrame()
for i in df.groupby(["stamp_card_id", "merchant_id", "user_id"]):
user_df = i[1]
if len(user_df)>1:
# get list of unique indexes in that groupby df
index = user_df.index.values
for ind in index:
fdf = user_df[ind:ind+np.timedelta64(1, 'h')]
if len(fdf.merchant_store_id.unique())>1:
fi_df=fi_df.append(fdf)
fi_df.drop_duplicates(keep="first").to_csv(csv_export_path)

分组后的样本数据为:

((117, 209, 'oZOfOgAgnO'),     stamp_card_id          stamp_time  stamps_record_id     user_id  
0             117 2018-10-14 16:48:03              1756  oZOfOgAgnO   
1             117 2018-10-14 16:54:03              1759  oZOfOgAgnO   
2             117 2018-10-14 16:58:03              1760  oZOfOgAgnO   
3             117 2018-10-14 17:48:03              1763  oZOfOgAgnO   
4             117 2018-10-14 18:48:03              1765  oZOfOgAgnO   
5             117 2018-10-14 19:48:03              1767  oZOfOgAgnO   
6             117 2018-10-14 20:48:03              1769  oZOfOgAgnO   
7             117 2018-10-14 21:48:03              1771  oZOfOgAgnO   
8             117 2018-10-15 22:48:03              1773  oZOfOgAgnO   
9             117 2018-10-15 23:08:03              1774  oZOfOgAgnO   
10            117 2018-10-15 23:34:03              1777  oZOfOgAgnO   
merchant_id  merchant_store_id  
0           209                662  
1           209                662  
2           209                662  
3           209                662  
4           209                662  
5           209                662  
6           209                663  
7           209                664  
8           209                662  
9           209                664  
10          209                663  )

我也尝试过重新采样的方法,但后来我得到了各个时间的数据,其中在小时结束时忽略了用户点击多个merchant_store_id的条件。

如有任何帮助,我们将不胜感激。感谢

如果这些是日期时间,您可以使用以下内容进行筛选:

filtered_set = set(df[df["stamp_time"]>=x][df["stamp_time"]<=y]["col of interest"])

df[df["stamp_time"]>=x]过滤df添加[df["stamp_time"]<=y]过滤过滤后的df["merchant_store_id"]只捕获指定的列(系列(最后CCD_ 4返回唯一列表(集合(


特定于您的代码:

x = datetime(lowerbound) #pseudo-code
y = datetime(upperbound) #pseudo-code
filtered_set = set(fi_df[fi_df["stamp_time"]>=x][fi_df["stamp_time"]<=y]["col of interest"])

最新更新