python - 是否有一种基于数据框中熊猫条件分配值的pythonic方法?
问题描述
我目前遇到以下问题:我有一个包含不同用户、应用程序和通知记录的数据框。对于每个用户和应用程序,我需要检查是否与通知进行了交互——如果用户在收到通知后与相应的应用程序进行了交互。如果是这样,我将第一个应用程序交互的时间戳分配给该应用程序的所有先前通知。
输入如下所示:
df = pd.DataFrame(np.array([[1,'a','notification',1], [1,'b','notification',2], [1,'b','app',3],
[1,'a','notification',4], [1,'a','app',5], [1,'a','notification',6],
[1,'a','app',7], [2,'a','notification',8]]), columns=['user','app', 'type', 'timestamp'])
结果应如下所示:
df_result = pd.DataFrame(np.array([[1,'a','notification',1,5], [1,'b','notification',2,3], [1,'b','app',3,0],
[1,'a','notification',4,5], [1,'a','app',5,0], [1,'a','notification',6,7],
[1,'a','app',7,0], [2,'a','notification',8,0]]), columns=['user','app', 'type', 'timestamp','interacted'])
目前,我使用以下代码运行代码:
def compute_groups(x):
x.loc[(x.type == "app"), "tmp"] = 1
x["sequence_id"] = x.tmp.cumsum()
x.sequence_id = x.sequence_id.shift(1, fill_value=0)
x = x.drop('tmp', axis=1)
return x
def compute_interactions(x):
x['interacted'] = x[x.type == 'app']['timestamp']
x.interacted.bfill(inplace=True)
return x
df["tmp"] = 0
df = df.groupby(['user','app']).apply(compute_groups)
df = df.groupby(['user','app','sequence_id']).apply(compute_interactions)
df['interacted'] = df.apply(lambda x: 0 if x.type == 'app' else x.interacted, axis=1)
当前代码似乎可以工作,但运行时间很长。输入数据帧有超过 60 万条记录。我认为有一些更 Pythonic 的方法可以做到这一点,可能与 groupby 和 shift 相结合。
解决方案
推荐阅读
- excel - 选择范围内的随机单元格
- xamarin.forms - 如何将本地 SDK 添加到 Xamarin 表单应用程序?
- c++ - “在不同的源文件中分离模块接口/实现单元”和使用“私有模块片段”之间的权衡是什么
- node.js - 在尝试运行“Hello World”练习后,遇到此错误代码 ENOENT: no such file or directory
- c++ - 如何确定 [start,stop) 范围内的元素是否都相等?
- python - SettingWithCopyWarning 问题
- python - Python 硒代理
- c++ - 基于 GTest 的测试二进制文件在构建时失败
- javascript - 带有 indexOf 的 JavaScript 字符串数组或带有字符串作为字段名的对象
- sql - 如何在 oracle 中将日期列默认为比另一个日期列提前 21 天?