Python - convert values if column and row names are the same

Viewed 100

I have a df as below - what I want to do is to convert 1 to 0 if ONLY the column names are equal to row names.

print(df)

         name  seq102681  seq103  seq11
0     seq102681     1       0      0
1      seq103       0       1      0
2       seq11       1       1      1

the desired output should be:

         name  seq102681  seq103  seq11
0     seq102681     0       0      0
1      seq103       0       0      0
2       seq11       1       1      0

I tried using intersection but it does not work.

import pandas as pd
df = pd.read_csv('file.csv')

intersection = df.index & df.columns
for item in intersection:
    df.loc[item, item] = 0
print(df)

Note: there are sometimes multiple rows with the same name but all of the column names are unique.

Thank you.

3 Answers

in fact, you want to change the diagonal of dataframe (Matrix). so you can use this code:

df.values[[np.arange(df.shape[0])]*2] = 0

you can do this using Numpy also:

import numpy as np
np.fill_diagonal(df.values, 0)
col_list = list(df.columns)
col_list.remove('name')

for col in col_list:
  df.loc[df['name'] == col, col] = 0
  
   for col in df.columns:
        df.loc[df['name'] == col, col] = 0
Related