Tuesday, 20 October 2020

How to calculate a Pandas DataFrame time difference between two columns in Python

 datetime objects can be placed in Pandas DataFrame columns. Two columns can be subtracted to return a series of timedelta objects representing the time difference between each row in the two columns.

USE pandas.to_datetime() TO CALCULATE A PANDAS DATAFRAME TIME DIFFERENCE BETWEEN TWO COLUMNS

Call pandas.to_datetime(column) with column as a column of time strings to return a Pandas Series of datetime objects. Use the syntax df.second - df.first to subtract the first column from the second column.

df = pd.DataFrame(columns=["one", "two"])


df.one = ["2019-01-24","2019-01-27"]
df.one = pd.to_datetime(df.one)

df.two = ["2019-01-28", "2020-01-29"]
df.two = pd.to_datetime(df.two)

print(df)
OUTPUT
         one        two
0 2019-01-24 2019-01-28
1 2019-01-27 2020-01-29

difference = (df.two - df.one)

print(difference)
OUTPUT
0     4 days
1   367 days
dtype: timedelta64[ns]


from : https://www.kite.com/python/answers/how-to-calculate-a-pandas-dataframe-time-difference-between-two-columns-in-python

No comments:

Post a Comment

How to check if a file contains a specific string using Bash

 In case if you want to check whether file does not contain a specific string, you can do it as follows. if ! grep -q SomeString "$File...