首页 > 解决方案 > 熊猫组内的渐进式价值收集

问题描述

我有一些类似的数据:

#Simulate some data
d = {
    "id": [1,1,1,1,1,2,2,2,2],
    "action_order": [1,2,3,4,5,1,2,3,4],
    "n_actions": [5,5,5,5,5,4,4,4,4],
    "seed": ['1','2','3','4','5','10','11','12','13'],
    "time_spent": [0.3,0.4,0.5,0.6,0.7,10.1,11.1,12.1,13.1]
    }
data = pd.DataFrame(d)

我需要一个函数,该函数将为每一行返回该行中两列(seed 和 time_spent)的值以及该组中的所有先前行作为字典。我尝试如下使用 apply 函数,但结果并不完全符合我的需要。

data \
    .groupby(["profile_id"])[["artist_seed", "tlh"]] \
    .apply(lambda x: dict(zip(x["artist_seed"], x["tlh"]))) \
    .tolist()

data \
    .groupby("profile_id")[["artist_seed", "tlh", "action_order"]] \
    .apply(lambda x: dict(zip(list(x["artist_seed"]), list(x["tlh"]))))

新的 DataFrame 应该如下所示:

   id                            new_col
0   1                        {u'1': 0.3}
1   1             {u'1': 0.3, u'2': 0.4}
2   1  {u'1': 0.3, u'3': 0.5, u'2': 0.4}
...

标签: pythonpandas

解决方案


您可以保持运行dict,并在每次迭代中返回最新版本的副本apply,每组:

def wrapper(g):
    cumdict = {}
    return g.apply(update_cumdict, args=(cumdict,), axis=1)

def update_cumdict(row, cd):
    cd[row.seed] = row.time_spent
    return cd.copy()

data["new_col"] = data.groupby("id").apply(wrapper).reset_index()[0]

data.new_col
0                                           {'1': 0.3}
1                                 {'1': 0.3, '2': 0.4}
2                       {'1': 0.3, '2': 0.4, '3': 0.5}
3             {'1': 0.3, '2': 0.4, '3': 0.5, '4': 0.6}
4    {'1': 0.3, '2': 0.4, '3': 0.5, '4': 0.6, '5': ...
5                                         {'10': 10.1}
6                             {'10': 10.1, '11': 11.1}
7                 {'10': 10.1, '11': 11.1, '12': 12.1}
8     {'10': 10.1, '11': 11.1, '12': 12.1, '13': 13.1}
Name: new_col, dtype: object

推荐阅读