How to move content of a column to a column next to it

Viewed 22

The dataframe looks like this:

import pandas as pd 

df = pd.DataFrame ({
    'Name':['Brian','John','Adam'],
    'HomeAddr':[12,32,44],
    'Age':['M','M','F'],
    'Genre': ['NaN','NaN','NaN']
    })

The current output is:

    Name  HomeAddr Age Genre
0  Brian        12   M   NaN
1   John        32   M   NaN
2   Adam        44   F   NaN

I would like to shift somehow content of HomeAddr and Age columns to columns+1. Below is a sample of the expected output.

    Name HomeAddr  Age Genre
0  Brian      NaN   12     M
1   John      NaN   32     M
2   Adam      NaN   44     F

I tried with .shift() but it doesn't work.

import pandas as pd 

df = pd.DataFrame ({
    'Name':['Brian','John','Adam'],
    'HomeAddr':[12,32,44],
    'Age':['M','M','F'],
    'Genre': ['NaN','NaN','NaN']
    })

df['HomeAddr'] = df['HomeAddr'].shift(-1)
print(df)


    Name  HomeAddr Age Genre
0  Brian      32.0   M   NaN
1   John      44.0   M   NaN
2   Adam       NaN   F   NaN

Any ideas guys? Thank you!

1 Answers

Use DataFrame.shift, but is necessary convert columns to strings for avoid missing values, then convert numeric columns back:

df.loc[:, 'HomeAddr':] = df.loc[:, 'HomeAddr':].astype(str).shift(1, axis=1)
df['Age'] = pd.to_numeric(df['Age'])
print (df)
    Name HomeAddr Age Genre
0  Brian      NaN  12     M
1   John      NaN  32     M
2   Adam      NaN  44     F

Another out of box solution:

df = df.drop('Genre', axis=1).rename(columns={'HomeAddr':'Age', 'Age':'Genre'})
df.insert(1, 'HomeAddr', np.nan)
print (df)
    Name  HomeAddr  Age Genre
0  Brian       NaN   12     M
1   John       NaN   32     M
2   Adam       NaN   44     F
Related