Search code examples
pythonpandastimeepoch

How can I add 1s in a python pandas column like row(n)=row(n-1)+1?


I need to create a simple python-pandas column looking like this :

(1607674395.805080)
(1607674396.805080)
(1607674397.805080)
(1607674398.805080)
(1607674399.805080)

Where the first row is (time.time()) (time since epoch) and I would like to add 1s juste like row(n)=row(n-1)+1s until the end of the next column called 'data' for exemple.


Solution

  • you can use shift method:

    import pandas as pd 
    import numpy as np
    import time
    pd.set_option('display.float_format', lambda x: '%.3f' % x)
    df = pd.DataFrame(dict(a=np.random.random(5)))
    df['new'] = np.arange(df.shape[0]) + time.time() # <<< this is the line that does the magic
    df['strs'] = '(' + df['new'].round(6).astype(str) + ')'
    >>> df
    
        a       new             strs
    0   0.119   1607948475.922  (1607948475.922189)
    1   0.716   1607948476.922  (1607948476.922189)
    2   0.561   1607948477.922  (1607948477.922189)
    3   0.188   1607948478.922  (1607948478.922189)
    4   0.995   1607948479.922  (1607948479.922189)