Resetting index of Pandas Series with a lambda expression

Viewed 184

I have a Pandas series, ts.

Date
2020-06-02    10.02
2020-06-03    10.45
2020-06-04    10.95
2020-06-05    11.23

For plotting purposes, I convert the index into strings by first converting it into a dataframe. Then apply a lambda expression followed by extracting it out as a Pandas series.

dfn = ts.to_frame()
dfn.index = dfn.reset_index().apply(lambda x: x['Date'].strftime('%Y-%m-%d'), axis=1)
tsn = dfn.iloc[:, 0]

Is there a more efficient way of doing it?

1 Answers

You can use rename with lambda function for cgange format of index:

ts = ts.rename(lambda x: x.strftime('%Y-%m-%d'))

Or another idea is use Series constructor with DatetimeIndex.strftime:

ts = pd.Series(ts.to_numpy(), index=ts.index.strftime('%Y-%m-%d'))

print (ts)
Date
2020-06-02    10.02
2020-06-03    10.45
2020-06-04    10.95
2020-06-05    11.23
dtype: float64

print (ts.index)
Index(['2020-06-02', '2020-06-03', '2020-06-04', '2020-06-05'], dtype='object', name='Date')
Related