Search code examples
pythonpython-3.xpandastimedeltapython-datetime

Customized inversion of a series of minutes in pandas


I have a pandas.Series of strings that represent minutes in a countdown manner, which I would like to invert for having it in an increasing chronological manner. That is, Consider the following Series:

pd.Series([ '30:00', '25:10', '22:30' ])
Out[1]:
0    30:00
1    25:10
2    22:30
dtype: object

Thee series' terms are minutes:seconds. I want to invert it and obtain seconds as integer values. That is, the highest is '30:00', which I would like to be the starting point, getting the value of 0. For '25:10' I would like to have 5*60-10=290. For '22:30' I want 7.5*60=450 and so on. Thus, I would like to obtain the following Series:

0    0
1    290
2    450
dtype: object

I know that the original series can be converted into datetime objects using pd.to_datetime. But am unsure how to invert it from countdown to increasing seconds.


Solution

  • A more general and pandas specific approach using to_timedelta:

    s = pd.to_timedelta('00:'+s).astype('timedelta64[s]')
    s = s.iloc[0] - s
    

    The resulting output:

    0      0.0
    1    290.0
    2    450.0