Home > other >  Dataframe: index values to compare
Dataframe: index values to compare

Time:11-03

I have a dataframe (below). I would like to compare the two values in the index column. The first index value is the value of the last index. The second index value is the value of index based on condition criteria (index which corresponds to 1).

In other words, how do I have d2 in the same format as d1 (I would like d2 to be able to the value of index corresponding to 1)? (as afterwards I would like to calculate the numeric difference between d1 and d2)(Something like df1.index[-1]-df1.index[ ]).days = 3)

Thanks in advance

import pandas as pd
df1 = pd.DataFrame({"date": ['2021-3-22', '2021-3-23', '2021-3-24', '2021-3-25', '2021-3-26'],
"x": ['nan', 1, 'nan', 'nan', 'nan' ]})
df1['date'] = pd.to_datetime(df1['date'])
df1.set_index('date', inplace=True)
df1

date         x
2021-03-22  nan
2021-03-23  1
2021-03-24  nan
2021-03-25  nan
2021-03-26  nan

d1 = df1.index[-1]
d1
Timestamp('2021-03-26 00:00:00')

d2=df1.x[df1.x == 1]
d2
date
2021-03-23    1
Name: x, dtype: object

(I would like to have d1-d2 =3)

PS In case, this is a followup question to Dataframe: index values difference calculation

CodePudding user response:

# subtract the index (which are datetime) and take the difference as days
(df1.index[-1] - df1[df1.x == 1].index).days[0]

>>> 3
  • Related