I have a pandas dataframe:
Col 1 | Col 2 |
---|---|
0 | 4 |
2 | 5 |
0 | 2 |
0 | 1 |
5 | 7 |
0 | 5 |
I want to replace Col 1 values with corresponding Col 2 values. But it should replace the value only if Col 1 value = 0. And once the column values is replaced the value that was replaced should get zero. Basically I want to swap the values.
Desired output should be:
Col 1 | Col 2 |
---|---|
4 | 0 |
2 | 5 |
2 | 0 |
1 | 0 |
5 | 7 |
5 | 0 |
Please help with the code.
CodePudding user response:
Use boolean indexing:
# identify rows to swap
m = df['Col 1'].eq(0)
# swap values
df.loc[m, ['Col 1', 'Col 2']] = df.loc[m, ['Col 2', 'Col 1']].to_numpy()
Updated DataFrame:
Col 1 Col 2
0 4 0
1 2 5
2 2 0
3 1 0
4 5 7
5 5 0
CodePudding user response:
df['Col 1']=df.apply(lambda row: row['Col 2'] if row['Col 1']==0 else row['Col 1'],axis=1)
df
Out[255]:
Col 1 Col 2
0 4 4
1 2 5
2 2 2
3 1 1
4 5 7
5 5 5
CodePudding user response:
You can use mask
:
# Columns to swap on condition
cols = ['Col 1', 'Col 2']
cond = df['Col 1'] == 0
df[cols] = df[cols].mask(cond, other=df[cols[::-1]].to_numpy())
Output:
Col 1 | Col 2 |
---|---|
4 | 0 |
2 | 5 |
2 | 0 |
1 | 0 |
5 | 7 |
5 | 0 |
CodePudding user response:
We can swap values between two columns by using Numpy where.
# Importing Modules
import pandas as pd
import numpy as np
# Creating DataFrame
df = pd.DataFrame({'col1': [0, 2, 0, 0, 5, 0], 'col2':[4, 5, 2, 1, 7, 5]})
# Swaping values between two columns based on the condition
df['col1'],df['col2']=np.where(df['col1']==0,(df['col2'],df['col1']),(df['col1'],df['col2']))
Final Output
col1 col2
0 4 0
1 2 5
2 2 0
3 1 0
4 5 7
5 5 0