I have some data (up to Event) and expected output (Key, Time) as follows:
+----------+------------+-------+-----+------+
| Location | Date | Event | Key | Time |
+----------+------------+-------+-----+------+
| i2 | 2019年03月02日 | 1 | a | |
| i2 | 2019年03月02日 | 1 | a | |
| i2 | 2019年03月02日 | 1 | a | |
| i2 | 2019年03月04日 | 1 | a | 2 |
| i2 | 2019年03月15日 | 2 | b | 0 |
| i9 | 2019年02月22日 | 2 | c | 0 |
| i9 | 2019年03月10日 | 3 | d | |
| i9 | 2019年03月10日 | 3 | d | 0 |
| s8 | 2019年04月22日 | 1 | e | |
| s8 | 2019年04月25日 | 1 | e | |
| s8 | 2019年04月28日 | 1 | e | 6 |
| t14 | 2019年05月13日 | 3 | f | |
+----------+------------+-------+-----+------+
Whenever Location or Event (or both) changes, a new Key is created. I'm mainly interested in the Time output, which is the difference in days between the first and last row of each Key. If there's one row in Key, the Time is 0. Do we still need to create Key or can directly get the Time gap?
asked Jun 3, 2019 at 17:21
srkdb
8254 gold badges16 silver badges30 bronze badges
2 Answers 2
I do not think you need create the Key here
df['Time']=df.groupby(['Location','Event']).Date.\
transform(lambda x : (x.iloc[-1]-x.iloc[0]))[~df.duplicated(['Location','Event'],keep='last')]
df
Out[107]:
Location Date Event Key Time
0 i2 2019年03月02日 1 a NaT
1 i2 2019年03月02日 1 a NaT
2 i2 2019年03月02日 1 a NaT
3 i2 2019年03月04日 1 a 2 days
4 i2 2019年03月15日 2 b 0 days
5 i9 2019年02月22日 2 c 0 days
6 i9 2019年03月10日 3 d NaT
7 i9 2019年03月10日 3 d 0 days
8 s8 2019年04月22日 1 e NaT
9 s8 2019年04月25日 1 e NaT
10 s8 2019年04月28日 1 e 6 days
11 t14 2019年05月13日 3 f 0 days
answered Jun 3, 2019 at 17:28
BENY
324k22 gold badges176 silver badges250 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
A vectorized approach
df['Date'] = pd.to_datetime(df['Date'])
df['diff'] = df['Key'].ne(df['Key'].shift(-1).ffill()).astype(int)
x = df.groupby(['Location','Event'])['Date'].transform(np.ptp)
df.loc[df['diff'] == 1, 'date_diff'] = x
df
Location Date Event Key Time diff date_diff
1 i2 2019年03月02日 1 a 0 NaT
2 i2 2019年03月02日 1 a 0 NaT
3 i2 2019年03月02日 1 a 0 NaT
4 i2 2019年03月04日 1 a 2 1 2 days
5 i2 2019年03月15日 2 b 0 1 0 days
6 i9 2019年02月22日 2 c 0 1 0 days
7 i9 2019年03月10日 3 d 0 NaT
8 i9 2019年03月10日 3 d 0 1 0 days
9 s8 2019年04月22日 1 e 0 NaT
10 s8 2019年04月25日 1 e 0 NaT
11 s8 2019年04月28日 1 e 6 1 6 days
12 t14 2019年05月13日 3 f 0 NaT
answered Jun 3, 2019 at 18:33
Vishnudev Krishnadas
11k2 gold badges29 silver badges58 bronze badges
Comments
lang-py