I have a pandas dataframe I would like to se the diagonal to 0
import numpy
import pandas
df = pandas.DataFrame(numpy.random.rand(5,5))
df
Out[6]:
0
This solution is vectorized and very fast and unless the other suggested solution works for any column names and size of df matrix.
def pd_fill_diagonal(df_matrix, value=0):
mat = df_matrix.values
n = mat.shape[0]
mat[range(n), range(n)] = value
return pd.DataFrame(mat)
Performance on Dataframe of 507 columns and rows
% timeit pd_fill_diagonal(df, 0)
1000 loops, best of 3: 145 µs per loop