Data Frame value set to 1 based on condition

Viewed 31

there is two data frame

import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[0,1,0,0,1], [1,0,0,1,0], [0,1,1,0,0]]))
df

     0   1   2   3   4
0    0   1   0   0   1
1    1   0   0   1   0
2    0   1   1   0   0

ddff = pd.DataFrame(np.array([[3,2,1], [4,2,3], [3,1,4], [4,1,2], [2,3,1]]))
ddff

    0   1   2
0   3   2   1
1   4   2   3
2   3   1   4
3   4   1   2
4   2   3   1

Now, I need to modify df data frame row 0 values based on ddff data frame. ddff data frame row 0 consist [3,2,1] values, Now If df data frame columns 3, 2 and 1 have value 0 then set it to 1

expected output

    0  1  2  3  4
0   0  1  1  1  1
1   1  0  0  1  0
2   0  1  1  0  0
1 Answers

This will replace all elements in row 0 in df in columns given by row 0 in ddff

df.iloc[0][ddff.iloc[0].values] = 1
# Out:
#    0  1  2  3  4
# 0  0  1  1  1  1
# 1  1  0  0  1  0
# 2  0  1  1  0  0

Explanation: ddff.iloc[0].values reads the column names from row 0 in ddff.

Related