user1566200
user1566200

Reputation: 1838

Subtract two Pandas DataFrame time indexes from each other?

I have two DataFrames (say A and B), each with an index that is a pandas.tseries.index.DateTimeIndex class.

How do I find the number of days between each row of the DataFrames?

So that A.index - B.index would give me something like:

34
25
34

and so on.

Upvotes: 0

Views: 626

Answers (1)

Alexander
Alexander

Reputation: 109546

Assuming both indices contain the same number of date observations, you can zip them and calculate the differences using a list comprehension.

df1 = pd.DataFrame(np.random.randn(5, 2), index=pd.date_range('2015-1-1', periods=5, freq='M'))

df2 = pd.DataFrame(np.random.randn(5, 2), index=pd.date_range('2015-6-1', periods=5, freq='M'))

>>> [(d2.date() - d1.date()).days for d1, d2 in zip(df1.index, df2.index)]
Out[46]: [150, 153, 153, 153, 153]

Upvotes: 1

Related Questions