Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shift column in dataframe without deleting one

Here is my dataframe:

A B C
First row to delete row to shift
Second row to delete row to shift

And I want this output :

A B C
First row to shift
Second row to shift

I tried this code :
df.shift(-1, axis=1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A B C
row to delete row to shift
row to delete row to shift

The fact is, is there a way to keep the first column not modified ?

>Solution :

Be explicit, chose the columns to affect and reassign (or update):

df[['B', 'C']] = df[['B', 'C']].shift(-1, axis=1, fill_value='')

Or:

cols = ['B', 'C']
df[cols] = df[cols].shift(-1, axis=1, fill_value='')

# or
# df.update(df[cols].shift(-1, axis=1, fill_value=''))

Output:

        A             B C
0   First  row to shift  
1  Second  row to shift  

You can do the same per index/column:

cols = ['B', 'C']
idx = [1]
df.loc[idx, cols] = df.loc[idx, cols].shift(-1, axis=1, fill_value='')

# or
# df.update(df.loc[idx, cols].shift(-1, axis=1, fill_value=''))

Output:

        A             B    C
0   First           row  row
1  Second  row to shift     
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading