Python 矩阵中 While 循环的递增和递减

问题描述 投票:0回答:1

我在 pandas 数据帧类型中创建了一个 15 x 15 矩阵。我想按照以下逻辑对某些单元格进行更改:

  • 矩阵的对角线设置为0
  • 在每一行中,如果任何位置出现 0,则后/前 5 列的值应更新为 1。 (df.iloc[i][j] = 0 --> df.iloc[i][j +5] = 1 或 df.iloc[i][j-5] = 1

输入(每个单元格为0.9):

row, col = 15, 16
a = pd.DataFrame.from_records([[0.9]*col]*row)
a = a.loc[ : , a.columns != 0]

enter image description here

预期输出: enter image description here

下面是我当前的脚本(一直运行没有结束):

row, col = 15, 16
a = pd.DataFrame.from_records([[0.9]*col]*row)
a = a.loc[ : , a.columns != 0]
column3 = list(a)
for i, j in a.iterrows():
    for k in column3:
        if k == i + 1:
            a.iloc[i][k] = 0


for i, j in a.iterrows():
    for k in column3:
        step = +5 if k <=5 else -5
        while k <= len(a.index):
            if a.iloc[i][k] == 0:
                k += step
                a.iloc[i][k] = 1

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
a 

非常感谢您的帮助!

python pandas dataframe matrix while-loop
1个回答
0
投票

IIUC用途:

m1 = a.eq(0)
m2 = a.where(m1).ffill(limit=5, axis=1).bfill(limit=5, axis=1).eq(0)

df = a.mask(m2 & ~m1, 1)
print (df)
     1    2    3    4    5    6    7    8    9    10   11   12   13   14   15
0   0.0  1.0  1.0  1.0  1.0  1.0  0.9  0.9  0.9  0.9  0.9  0.9  0.9  0.9  0.9
1   1.0  0.0  1.0  1.0  1.0  1.0  1.0  0.9  0.9  0.9  0.9  0.9  0.9  0.9  0.9
2   1.0  1.0  0.0  1.0  1.0  1.0  1.0  1.0  0.9  0.9  0.9  0.9  0.9  0.9  0.9
3   1.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0  1.0  0.9  0.9  0.9  0.9  0.9  0.9
4   1.0  1.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0  1.0  0.9  0.9  0.9  0.9  0.9
5   1.0  1.0  1.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0  1.0  0.9  0.9  0.9  0.9
6   0.9  1.0  1.0  1.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0  1.0  0.9  0.9  0.9
7   0.9  0.9  1.0  1.0  1.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0  1.0  0.9  0.9
8   0.9  0.9  0.9  1.0  1.0  1.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0  1.0  0.9
9   0.9  0.9  0.9  0.9  1.0  1.0  1.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0  1.0
10  0.9  0.9  0.9  0.9  0.9  1.0  1.0  1.0  1.0  1.0  0.0  1.0  1.0  1.0  1.0
11  0.9  0.9  0.9  0.9  0.9  0.9  1.0  1.0  1.0  1.0  1.0  0.0  1.0  1.0  1.0
12  0.9  0.9  0.9  0.9  0.9  0.9  0.9  1.0  1.0  1.0  1.0  1.0  0.0  1.0  1.0
13  0.9  0.9  0.9  0.9  0.9  0.9  0.9  0.9  1.0  1.0  1.0  1.0  1.0  0.0  1.0
14  0.9  0.9  0.9  0.9  0.9  0.9  0.9  0.9  0.9  1.0  1.0  1.0  1.0  1.0  0.0
© www.soinside.com 2019 - 2024. All rights reserved.