4

I want to add a list of minutes to datetime64 columns into a new df column.

I tried using datetime.timedelta(minutes=x) in a for loop. But as a result, it is adding a constant value to all of my rows. How do I resolve this?

for x in wait_min:
    data['New_datetime'] = data['Date'] + datetime.timedelta(minutes=x)

I expect to iterate through the list and add corresponding minutes, but this is adding a constant value of 16 minutes to each row.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Rick707
  • 63
  • 1
  • 5

3 Answers3

4

Let us try

data['Date'] + pd.to_timedelta(wait_min, unit='m')
BENY
  • 317,841
  • 20
  • 164
  • 234
1

The following changes worked for me:

for i, x in enumerate(wait_min):
     data['New_Datetime'].iloc[i] = data['Date'].iloc[i] + datetime.timedelta(minutes=x)

might not be the best solution, but this works for what I was trying to do.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Rick707
  • 63
  • 1
  • 5
1

pandas sums two Series element-wise, if they have the same length. All you need to do is create a Series of timedelta objects.

So if wait_min is a list of minutes of length equal to the number of rows in your dataframe, this will do:

data['New_datetime'] = data['Date'] + pd.Series([datetime.timedelta(minutes=x) for x in wait_min])
Valentino
  • 7,291
  • 6
  • 18
  • 34
  • Thanks valentino. This seems more efficient. I will try this. – Rick707 Aug 03 '19 at 01:46
  • 2
    @Valentino, I personally make it a habit to upvote questions I answered. I think that if a question is worth answering, it is worth an upvote. In addition, the OP can not upvote your answer until they have 15 reputation. So I suggest helping them along their path to becoming good Stack Overflow citizens, by upvoting their good quesions. Cheers. – Stephen Rauch Aug 03 '19 at 02:01