有没有一种pythonic方法可以根据数据框中的熊猫条件分配值?

时间:2020-07-29 09:17:18

标签: python pandas dataframe lookup

我目前遇到以下问题:我有一个包含不同用户,应用程序和通知记录的数据框。对于每个用户和应用程序,我需要检查通知是否已与-用户在收到通知后是否与相应的应用程序进行了交互。如果是这样,我将首次应用程序交互的时间戳记分配给该应用程序的所有先前通知。

输入内容如下:

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万条记录。我认为还有更多的Python方式可以做到这一点,可能是将groupby和shift结合在一起。

0 个答案:

没有答案
相关问题