0

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
0

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.