且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在pandas.DataFrame的对角线上设置值

更新时间:2023-11-23 07:59:16

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

In [22]: df
Out[22]: 
          0         1         2         3         4
0  0.000000  0.931374  0.604412  0.863842  0.280339
1  0.531528  0.000000  0.641094  0.204686  0.997020
2  0.137725  0.037867  0.000000  0.983432  0.458053
3  0.594542  0.943542  0.826738  0.000000  0.753240
4  0.357736  0.689262  0.014773  0.446046  0.000000

请注意,这仅在df具有与列相同的行数时才有效.适用于任意形状的另一种方法是使用 np.fill_diagonal :

Note that this will only work if df has the same number of rows as columns. Another way which will work for arbitrary shapes is to use np.fill_diagonal:

In [36]: np.fill_diagonal(df.values, 0)