python - 熊猫组内的渐进式价值收集
问题描述
我有一些类似的数据:
#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}
...
解决方案
您可以保持运行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
推荐阅读
- java - 生成以 x 开头的随机数列表
- javascript - 无法使用 mongoose.find 查询日期
- ios - 无法将“testViewController.Type”类型的值转换为预期的参数类型“UIViewController”
- c - 处理每个客户的线程是这个项目的最佳解决方案吗?
- rest - Spring WebFlux REST API - 消息驱动
- go - 将 gRPC 类型正确处理为 SQL ORM
- android - 根据在同一类中单击的按钮更改文本内容
- kotlin - Kotlin 解构超过五个组件
- django - 在不使用重定向的情况下提交表单后更改 url
- python - 在 Telebot 中开发的机器人在私人消息中工作,而不是在群组中工作