pandas对角线值修改

思路:

1、先将DataFrame数据转换为numpy

2、通过numpy来修改对角线值

3、再将数据转换为DataFrame

代码:

import pandas as pd
import numpy as np

# 数据
df = pd.DataFrame(np.arange(16).reshape((4, 4)), index=[‘a‘, ‘b‘, ‘c‘, ‘d‘], columns=[‘i‘, ‘j‘, ‘k‘, ‘f‘])
>>df:
     i    j    k    f
a    0    1    2    3
b    4    5    6    7
c    8    9    10    11
d    12   13   14    15


# 转换为numpy
dia_dt = df.values
>>dia_dt:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])

# 修改对角线数据
dia_i = list(range(len(df)))  # 获取numpy对角线索引
>>dia_i:
[0, 1, 2, 3]

dia_dt[dia_i, dia_i] = 0  # 通过索引修改值
>>dia_dt:
array([[ 0,  1,  2,  3],
       [ 4,  0,  6,  7],
       [ 8,  9,  0, 11],
       [12, 13, 14,  0]])

# 将数据转换回DataFrame
df = pd.DataFrame(dia_dt, index=df.index, columns=df.columns)
>>df:
     i    j    k    f
a    0    1    2    3
b    4    0    6    7
c    8    9    0    11
d    12   13   14   0