m13op22
m13op22

Reputation: 2337

Converting timedeltas to integers for consecutive time points in pandas

Suppose I have the dataframe

import pandas as pd

df = pd.DataFrame({"Time": ['2010-01-01', '2010-01-02', '2010-01-03', '2010-01-04']})

print(df)

              Time
  0     2010-01-01
  1     2010-01-02
  2     2010-01-03
  3     2010-01-04

If I want to calculate the time from the lowest time point for each time in the dataframe, I can use the apply function like

df['Time'] = pd.to_datetime(df['Time'])
df.sort_values(inplace = True)

df['Time'] = df['Time'].apply(lambda x: (x - df['Time'].iloc[0]).days)

print(df)

     Time
  0     0
  1     1
  2     2
  3     3

Is there a function in Pandas that does this already?

Upvotes: 0

Views: 32

Answers (1)

BENY
BENY

Reputation: 323226

I will recommend not use apply

(df.Time-df.Time.iloc[0]).dt.days
0    0
1    1
2    2
3    3
Name: Time, dtype: int64

Upvotes: 1

Related Questions