Rtut Rtut - 3 months ago 16
Python Question

replace values in dataframe here rowname is equals to column name

I have a dataframe with binary values. I want to change values to zero where row and column name is same. What is the easiest way to do this?

tmp_dict= {'x':[0,0,0,0,0],'y':[1,0,1,0,0],'z':[1,1,1,1,1],'p':[0,1,1,0,1],'q':[0,1,1,1,1]}
mydf= pd.DataFrame(tmp_dict, columns=['x','y','z','p','q'], index=['x','y','z','p','q'])
mydf
x y z p q
x 0 1 1 0 0
y 0 0 1 1 1
z 0 1 1 1 1
p 0 0 1 0 1
q 0 0 1 1 1


Desired dataframe:

x y z p q
x 0 1 1 0 0
y 0 0 1 1 1
z 0 1 0 1 1
p 0 0 1 0 1
q 0 0 1 1 0

Answer

You can loop through the columns and set the corresponding row(s) to zero using loc.

for col in mydf:
    mydf.loc[col, col] = 0
Comments