1

I want to create a new column in my DataFrame equal to the Index column but shifted 1 position upwards.

I know how to use the shift function to a columns that can be referred to in a df['column_name'] way, but I don't know how to do this with the index column.

I have tried df.index.shift(-1) but it doesn't work. df['index_name'].shift(-1) doesn't work either.

The desired result of would be to create a column which the index but shifted, just as if I did df['column2'] = df['column1'].shift(-1).

2 Answers 2

5

Use Index.to_series, because shift is not implemented for some Index like RangeIndex yet:

df["index_shifted"] = df.index.to_series().shift(-1)

If check Index.shift:

Notes

This method is only implemented for datetime-like index classes, i.e., DatetimeIndex, PeriodIndex and TimedeltaIndex.

Sign up to request clarification or add additional context in comments.

Comments

3

This should work:

df["index_shifted"] = df.reset_index().iloc[:, 0].shift(-1)

The reset_index function put the index in the first column of the new DataFrame created and is selected by iloc. Then it is shifted backward by one step by the shift function.

Documentation of these functions:

reset_index

iloc

shift


Don't use this

@Jezrael's answer is a better choice, because more efficient, especially for big Dataframes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.