首页 > 解决方案 > 是否有一种基于数据框中熊猫条件分配值的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 相结合。

标签: pythonpandasdataframelookup

解决方案


推荐阅读