python - 如何在对角线上设置值并在所有行上重复?

标签 python pandas numpy

我有一个由 0 和不同数量的列填充的时间序列数据框,我想从第一行和第一列开始用 100 填充对角线的值。我可以使用下面问题中提出的解决方案,但它会在最后一列的值被填充后停止。
Set values on the diagonal of pandas.DataFrame

我怎样才能让它在所有行上重复?

这是我的数据框的样子:

                               A      B
2020-05-02 23:00:00+00:00    0.0    0.0
2020-05-03 00:00:00+00:00    0.0    0.0
2020-05-03 01:00:00+00:00    0.0    0.0
2020-05-03 02:00:00+00:00    0.0    0.0
2020-05-03 03:00:00+00:00    0.0    0.0

但是正如您所看到的,使用 Numpy fill_diagonal 并不能完成这项工作。
import numpy as np
np.fill_diagonal(df.values, 0)

                               A      B
2020-05-02 23:00:00+00:00  100.0    0.0
2020-05-03 00:00:00+00:00    0.0  100.0
2020-05-03 01:00:00+00:00    0.0    0.0
2020-05-03 02:00:00+00:00    0.0    0.0
2020-05-03 03:00:00+00:00    0.0    0.0

当有 2 列时,我想要的是这样的:
                               A      B
2020-05-02 23:00:00+00:00  100.0    0.0
2020-05-03 00:00:00+00:00    0.0  100.0
2020-05-03 01:00:00+00:00  100.0    0.0
2020-05-03 02:00:00+00:00    0.0  100.0
2020-05-03 03:00:00+00:00  100.0    0.0

最佳答案

这是一种基于 n​​umpy 的方法,根据列的数量进行整形,并使用给定的值分配回:

def fill_wrapped_diag(a, fill_val):
    r,c = a.shape
    r_left = c-r%c
    a_ext = np.pad(a, ((0,r_left),(0,0)))
    a_r = a_ext.reshape((r+r_left)//c, -1)
    a_r[:,::c+1] = fill_val
    return a_r.reshape(a_ext.shape)[:-r_left]
df[:] = fill_wrapped_diag(df.values, 100)
print(df)
                               A      B
2020-05-02-23:00:00+00:00  100.0    0.0
2020-05-03-00:00:00+00:00    0.0  100.0
2020-05-03-01:00:00+00:00  100.0    0.0
2020-05-03-02:00:00+00:00    0.0  100.0
2020-05-03-03:00:00+00:00  100.0    0.0

其他一些例子:
a = np.zeros((8,4))
fill_wrapped_diag(a, fill_val=100)

array([[100.,   0.,   0.,   0.],
       [  0., 100.,   0.,   0.],
       [  0.,   0., 100.,   0.],
       [  0.,   0.,   0., 100.],
       [100.,   0.,   0.,   0.],
       [  0., 100.,   0.,   0.],
       [  0.,   0., 100.,   0.],
       [  0.,   0.,   0., 100.]])

a = np.random.randint(0,10,(7,3))
fill_wrapped_diag(a, fill_val=75)

array([[75,  8,  8],
       [ 4, 75,  7],
       [ 3,  5, 75],
       [75,  5,  5],
       [ 5, 75,  2],
       [ 3,  6, 75],
       [75,  1,  8]])

关于python - 如何在对角线上设置值并在所有行上重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61651953/

相关文章:

python - 在 SQLAlchemy 查询中使用像 substr(X, Y, Z) 这样的 SQL 函数

python - 如何将字符串转换为整数并将它们相加?

python - Flask wtform RadioField 标签不呈现

python - 堆叠具有重叠索引的数组。寻找循环上的矢量化方法

python - 计算 CFD 网格中点之间的距离

python - For循环n次迭代-Python

python-3.x - 随机样本集,用于根据标签创建交叉验证和训练集

python - 使用现有数据框的附加条目构建数据框

python - 将 pandas MultiIndex DataFrame 从按行转换为按列

python - 将 ctypes int** 转换为 numpy 二维数组