Home > Back-end >  How to move one column values to another in pandas base on condition
How to move one column values to another in pandas base on condition

Time:03-15

My DataFrame is given below

df = pd.DataFrame({'name':['a', 'b', 'c', 'd'],
        'per1':[np.nan, 'sa1', 'sa2', np.nan],
        'per2':['sa3', 'sa2', 'sa2', 'sa4']})

which looks like:

name  per1  per2

a     NaN   sa3
b     sa1   sa2
c     sa2   sa2
d     NaN   sa4

and I want to convert to the the outcome below by moving per2 column values to per1 which has null values.

name  per1  per2

a     sa3  
b     sa1  sa2
c     sa2  sa2
d     sa4  

I have tried this one but it copy the per2 column value.

df['per1']=df['per1'].fillna(df['per2'])

CodePudding user response:

You could use loc:

msk = df['per1'].isna()
df.loc[msk, ['per1', 'per2']] = df.loc[msk, ['per2', 'per1']].to_numpy()

Output:

  name per1 per2
0    a  sa3  NaN
1    b  sa1  sa2
2    c  sa2  sa2
3    d  sa4  NaN
  • Related