我有一个用户与网站互动的日志:
id user_id action_type comment timestamp
并非所有 action_type 都相同。其中一些更重要,一些更少:
PURCHASE (important, primary)
VISIT_PAGE (less important, secondary)
我想将表格转换为以下内容:
id user_id action_type comment timestamp next_id goal_id
其中:
next_id 是未来最接近时间戳的用户的下一个操作
goal_id 是未来最接近时间戳的用户的下一个主要操作
例如,如果用户具有以下历史记录:
/ -> /toys -> /toys/lego -> /toys/lego/ABC001 -> PURCHASE
然后我有下表:
id user_id action_type comment timestamp next_id goal_id
1 1 VISIT_PAGE / 123456789 2 5
2 1 VISIT_PAGE /toys 123457789 3 5
3 1 VISIT_PAGE /toys/lego 123458889 4 5
4 1 VISIT_PAGE /toys/lego/ABC001 123459889 5 5
5 1 PURCHASE 123460889 NULL 5
可以使用 Pandas 完成吗?它与Oracle中的LEAD功能非常相似。
答案 0 :(得分:1)
假设您有一些主要操作类型列表:这是一种脏的方法。注意我并没有使用任何熊猫魔法,但希望这会给你一些想法:
primaries = set("two") # set of primary actions
# an example dataframe
df = pd.DataFrame([[1,1,1,1,1],
["one"] * 4 + ["two"] * 1,
["/", "toys", "toys/lego", "toys/lego/ABC001"],
[1001, 1002, 1003, 1004, 1005]]
).T
df.columns = ["user_id", "action_type", "comment", "timestamp"]
# reindexing to make it look like your sample
df.index = range(1, len(df)+1)
df.head()
nt = [] # next_ids
gl = [] # goal_ids
for i in df.iterrows():
if i[1]["action_type"] not in primaries:
nt.extend([i[0]+1])
else:
nt.extend([None])
gl.extend([i[0]] * len(nt))
new_df = pd.merge(df, pd.DataFrame({"next_id" : nt], "goal_id" : ids[gl]}))