我在 pandas 数据帧类型中创建了一个 15 x 15 矩阵。我想按照以下逻辑对某些单元格进行更改:
输入(每个单元格为0.9):
row, col = 15, 16
a = pd.DataFrame.from_records([[0.9]*col]*row)
a = a.loc[ : , a.columns != 0]
下面是我当前的脚本(一直运行没有结束):
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
非常感谢您的帮助!
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.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