Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

python - How to find time gap if a column value and the succeeding value of another column is notna()

I have a data frame like below:

Datetime          | A     |   B   | C       |
----------------------------------------------   
12-03-2020 04:43  | 295   |       |         |
13-03-2020 15:42  |       | 3     | 3       |
14-03-2020 17:05  |       | 3.0   | 3.0     |
15-03-2020 17:25  | 295   |       |         |
16-03-2020 17:26  |       | 3.1   | 3.11    |
17-03-2020 18:14  | 295   |       |         |
18-03-2020 20:10  |       | 3.2   | 3.23    |

Here I need to find the time gap between column A and Column[B,C].

The code which I'm using is :

df['timegap_in_min'] = np.where( ((df['A'].notna()) &(df[['B','c']].shift(-1).notna())),df['Datetime'].shift(-1) - df['timestamp'], np.nan)
df['timegap_in_min'] = df['timegap_in_min'].astype('timedelta64[m]')

But this code shows the following error:

TypeError: Cannot perform 'rand_' with a dtyped [bool] array and scalar of type [float]

The actual output should be:

Datetime          | A     |   B   | C       |   timegap_in_min  |
---------------------------------------------- -------------------- 
12-03-2020 04:43  | 295   |       |         |   2099            |
13-03-2020 15:42  |       | 3     | 3       |                   |
14-03-2020 17:05  |       | 3.0   | 3.0     |                   |
15-03-2020 17:25  | 295   |       |         |   1               |
15-03-2020 17:26  |       | 3.1   | 3.11    |                   |
15-03-2020 18:14  | 295   |       |         |                   |
15-03-2020 20:10  |       | 3.2   | 3.23    |   115             |
question from:https://stackoverflow.com/questions/65878544/how-to-find-time-gap-if-a-column-value-and-the-succeeding-value-of-another-colum

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...