首页 > 解决方案 > 如何合并数据框中的一些数据

问题描述

我需要在数据框中合并一些数据,因为我将在 python 中编写[顺序关联规则]。

如何合并数据以及我应该在 python 中使用什么算法?先验的?FP增长?我在 python 中使用 apriori 找不到[顺序关联规则]。他们使用 R

访问地点为 250 个。唯一 ID 号为 116807,总行数为 170 万。而且,每个 id 都有 country_code(111 个国家,但我会将它们分类为 10 个国家).. 所以我将它们再合并一个。

以前的数据

index     date_ymd      id     visit_nm   country
1         20170801    123123    seoul      460
2         20170801    123123    tokyo      460
3         20170801    124567    seoul      440
4         20170802    123123    osaka      460
5         20170802    123123    seoul      460
...         ...         ...      ...

我需要的

index    Transaction           visit_nm      country
1        20170801123123      {seoul,tokyo}     460
2        20170802123123      {osaka,seoul}     460

标签: pythonpandas

解决方案


根据我看到数据的理解,使用 groupby agg:

s=pd.Series(df.date_ymd.astype(str)+df.id.astype(str),name='Transaction')
(df.groupby(s)
 .agg({'visit_nm':lambda x: set(x),'country':'first'}).reset_index())

      Transaction        visit_nm  country
0  20170801123123  {seoul, tokyo}      460
1  20170801124567         {seoul}      440
2  20170802123123  {osaka, seoul}      460

推荐阅读