简体   繁体   中英

Change the standard integer index of a pandas dataframe to a datetime index starting from minute 1 incremending by one minute

I have a pandas dataframe that has index starting from 1 onwards. I have been treating it as a time series because my problem actually involves minutes counting from minute 1 onwards, so it has been convenient. However, now I need to convert the index to DateTime to implement some statsmodels.

How can I do that if I don't want to redefine my entire work so far?

I've tried

df.index = pd.to_datetime(pd.index)

but this starts 1970-01-01 00:00:00.000000001. I would like this to start from "00:01:00" onwards, incrementing by 1 minute, any suggestions?

Use to_timedelta passing unit='m' (for minutes) as an argument.

df = pd.DataFrame({'A': ['x'] * 10})

df.index = pd.to_timedelta(pd.RangeIndex(1, len(df)+1), unit='m')
df    
          A
00:01:00  x
00:02:00  x
00:03:00  x
00:04:00  x
00:05:00  x
00:06:00  x
00:07:00  x
00:08:00  x
00:09:00  x
00:10:00  x

If your index is monotonically increasing, you can simplify the expression above to

df.index = pd.to_timedelta(df.index+1, unit='m')
df    
          A
00:01:00  x
00:02:00  x
00:03:00  x
00:04:00  x
00:05:00  x
00:06:00  x
00:07:00  x
00:08:00  x
00:09:00  x
00:10:00  x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM