How to shift all the values from a certain point of the dataframe to the right?

26 views Asked by At

Example: I have this dataset

        A     B     C     D     E
  0    0.1   0.2   0.3   0.4   0.5
  1    1.1   1.2   1.3   1.4   1.5
  2    2.1   2.2   2.4   2.5   2.6
  3    3.1   3.2   3.4   3.5   3.6
  4    4.1   4.2   4.4   4.5   4.6
  5    5.1   5.2   5.3   5.4   5.5

What I would like to have is:

        A     B     C     D     E
  0    0.1   0.2   0.3   0.4   0.5
  1    1.1   1.2   1.3   1.4   1.5
  2    2.1   2.2         2.4   2.5   2.6
  3    3.1   3.2         3.4   3.5   3.6
  4    4.1   4.2         4.4   4.5   4.6
  5    5.1   5.2   5.3   5.4   5.5

So I need to shift only certain rows and only certain columns to the right. Not all the lines and columns have to be affected by that shift. I hope it's clear, thank you.

1

There are 1 answers

0
iohans On

Pandas would be a lovely way to solve this. Use the .loc to select the rows and columns and use .shift() to move them to the right.

import pandas as pd

df.loc[2:4, ['C','D']] = df.loc[2:4, ['C','D']].shift(1, axis=1)

If you share your dataframe code to define df, I can fully test the loc/shift solution.