Set values on the diagonal of pandas.DataFrame

后端 未结 5 2222
日久生厌
日久生厌 2020-11-27 17:56

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           


        
5条回答
  •  忘掉有多难
    2020-11-27 18:23

    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

提交回复
热议问题