jul
jul

Reputation: 37484

Modify DataFrame index

I have a DataFrame with a wrong DateTimeIndex. The hours and minutes must be moved to the left:

2016-07-07 00:08:30 -> 2016-07-07 08:30:00

I know how to make the change with regex, but I do not know how to replace the index by the modified one. Something like df.index.replace(lambda old_index:new_index)...

Anybody can help?

Upvotes: 0

Views: 61

Answers (1)

BENY
BENY

Reputation: 323376

By using to_datetime with format

#idx=pd.Index(pd.to_datetime(pd.Series('2016-07-07 00:08:30')))

pd.to_datetime(pd.Series(idx).astype(str),format='%Y-%m-%d %S:%H:%M')
Out[562]: 
0   2016-07-07 08:30:00
dtype: datetime64[ns]

And for new index use:

df.index = pd.to_datetime(df.index.astype(str),format='%Y-%m-%d %S:%H:%M')

Upvotes: 1

Related Questions