当多列条件在python中匹配时添加行?

时间:2019-04-07 09:28:37

标签: python pandas

我正在尝试在数据框中添加一行。条件是当用户再次回到该应用程序(300秒后)时,我需要添加一行。下面是我的代码。它可以正常工作,但需要花费大量执行时间,因为实际数据帧有1000万行。

cursor.fetchall()

输入:

for i in range(1,len(df)):
    if df['user_id'][i]==df['user_id'][i-1] and (df['start_time'][i]-df['start_time'][i-1]).seconds>300:
        df.loc[len(df)]=[df['user_id'][i],df['start_time'][i],'psuedo_App_start_2']

输出应如下所示:

user_id   start_time        event
100       03/04/19 6:11     psuedo_App_start
100       03/04/19 6:11     notification_receive
100       03/04/19 8:56     notification_dismiss
10        03/04/19 22:05    psuedo_App_start
10        03/04/19 22:05    subcategory_click
10        03/04/19 22:06    subcategory_click

从输出中可以看到,user_id = 100添加了一行,因为他回到8.56,即300秒后返回。

2 个答案:

答案 0 :(得分:2)

首先按2个条件进行过滤-比较user_id和每个组的DataFrameGroupBy.shift个值,还比较每个组的差异和DataFrameGroupBy.diff,然后重新分配evet列和{{3 }},最后DataFrame.assign在一起,并按concat排序:

#MM/DD/YY HH:MM
#df['start_time'] = pd.to_datetime(df['start_time'])
#DD/MM/YY HH:MM
#df['start_time'] = pd.to_datetime(df['start_time'], dayfirst=True)

m1 = df['user_id'].eq(df.groupby('user_id')['user_id'].shift())
m2 = df.groupby('user_id')['start_time'].diff().dt.total_seconds() > 300

df1 = df[m1 & m2].assign(event='psuedo_App_start_2')

df1 = (pd.concat([df, df1], ignore_index=True)
         .sort_values(['user_id','start_time'], ascending=[False, True]))
print (df1)
   user_id          start_time                 event
0      100 2019-03-04 06:11:00      psuedo_App_start
1      100 2019-03-04 06:11:00  notification_receive
2      100 2019-03-04 08:56:00  notification_dismiss
6      100 2019-03-04 08:56:00    psuedo_App_start_2
3       10 2019-03-04 22:05:00      psuedo_App_start
4       10 2019-03-04 22:05:00     subcategory_click
5       10 2019-03-04 22:06:00     subcategory_click

答案 1 :(得分:0)

通常,在这种情况下,您需要将显式循环转换为矢量化操作。尝试这样的事情:

i = (df.user_id.values[1:] == df.user_id.values[:-1]) & ((df.start_time.values[1:] - df.start_time.values[:-1])/np.timedelta64(1, 's') > 300)
newRows = tt[np.append(False, i)].copy()
newRows.event = 'psuedo_App_start_2'
df.append(newRows)