How to shift several rows in a pandas DataFrame?

You can transpose the initial DF so that you have a way to access the row labels as column names inorder to perform the shift operation.

Shift the contents of the respective columns downward by those amounts and re-transpose it back to get the desired result.

df_t = df.T
df_t.assign(a=df_t['a'].shift(2), b=df_t['b'].shift(1)).T

enter image description here


IMHO, this is a more pythonic way:

df.loc['a'] = df.loc['a'].shift(periods=2,axis=0)

Note in this case .loc returns a Series, so axis=0 is optional.