python - Get first and last month in pandas dataframe where a specific value occurs -


i have foll. dataframe:

datetime    year    cal val 1/1/2000    2000    1   0.23 1/2/2000    2000    1   0.34 2/3/2000    2000    1   0.45 4/4/2000    2000    2   0.56 4/5/2000    2000    2   0.67 4/6/2000    2000    2   0.78 5/7/2000    2000    3   0.89 7/8/2000    2000    3   1 7/9/2000    2000    3   1.11 

the datatime column represents dataframe index.

i find month last cal == 1 value (this february). similarly, want find month first cal == 3 value (this may in example.). right now, can subset:

df[df.cal == 1] 

but not sure how proceed this.

use loc find subset matches condition, access first element of resulting index [0] , last element [-1]. use .month integer of relevant month.

"i find month last cal == 1 value (this february)."

>>> df.loc[df.cal == 1].index[-1].month 2 

"similarly, want find month first cal == 3 value (this may in example.). "

>>> df.loc[df.cal == 3].index[0].month 5 

Comments