3

I have a pandas dataset like this:

user_id      datetime
   1        13 days 21:50:00
   2        0 days 02:05:00
   5        10 days 00:10:00
   7        2 days 01:20:00
   1        3 days 11:50:00
   2        1 days 02:30:00

I want to have a column that contains the mintues, So in this case the result can be :

 user_id      datetime             minutes         
   1        13 days 21:50:00        20030
   2        0 days 02:05:00          125
   5        10 days 00:10:00        14402
   7        2 days 01:20:00          2960
   1        3 days 11:50:00          5030
   2        1 days 02:30:00          1590

Is there any way to do that without loop?

2
  • Uhm I don't think there's a way to calculate the minutes for every user_id and datetime without an explicit or implicit loop. Commented Apr 14, 2018 at 2:04
  • @DanieleCappuccio Definitely true. But I'd guess the OP is probably just not being that clear, and what he doesn't want is an explicit loop, either to avoid breaking the array-processing style, or to get the speedup of letting Numpy/Pandas do the looping in C. Commented Apr 14, 2018 at 2:22

2 Answers 2

10

Yes, there is a special dt accessor for date/time series:

df['minutes'] = df['datetime'].dt.total_seconds() / 60

If you only want whole minutes, cast the result using .astype(int).

Sign up to request clarification or add additional context in comments.

Comments

2

Here is a way with pd.Timedelta:

df['minutes'] = pd.to_timedelta(df.datetime) / pd.Timedelta(1, 'm')

>>> df
   user_id          datetime  minutes
0        1  13 days 21:50:00  20030.0
1        2   0 days 02:05:00    125.0
2        5  10 days 00:10:00  14410.0
3        7   2 days 01:20:00   2960.0
4        1   3 days 11:50:00   5030.0
5        2   1 days 02:30:00   1590.0

if your datetime column is already of dtype timedelta, you can omit the explicit casting and just use:

df['minutes'] = df.datetime / pd.Timedelta(1, 'm')

Comments

Your Answer

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.