gpt4 book ai didi

python - 裁剪矩阵的 nan 行和列,但保持正方形

转载 作者:太空狗 更新时间:2023-10-29 23:59:21 25 4
gpt4 key购买 nike

我有一个包含 > 1,000 行和列的方阵。在“边界”的许多字段中都有nan,例如:

grid = [[nan, nan, nan, nan, nan],
[nan, nan, nan, nan, nan],
[nan, nan, 1, nan, nan],
[nan, 2, 3, 2, nan],
[ 1, 2, 2, 1, nan]]

现在我想消除所有只有 nan 的行和列。这将是 1. 和 2. 行和最后一列。但是我也想接收一个方阵,所以被消去的行数必须等于被消去的列数。在这个例子中,我想得到这个:

grid = [[nan, nan, nan, nan],
[nan, nan, 1, nan],
[nan, 2, 3, 2],
[ 1, 2, 2, 1]]

我确定我可以用一个循环来解决这个问题:检查每一列和每一行是否只有 nan 里面,最后我使用 numpy.delete 删除我找到的行和列(但只有最少的数字,因为得到一个正方形)。但我希望任何人都可以帮助我提供更好的解决方案或好的库。

最佳答案

这是有效的,压缩 rows\cols 的索引是关键,因此它们始终具有相同的长度,从而保持矩阵的方形。

nans_in_grid = np.isnan(grid)
nan_rows = np.all(nans_in_grid, axis=0)
nan_cols = np.all(nans_in_grid, axis=1)

indicies_to_remove = zip(np.nonzero(nan_rows)[0], np.nonzero(nan_cols)[0])
y_indice_to_remove, x_indice_to_remove = zip(*indicies_to_remove)

tmp = grid[[x for x in range(grid.shape[0]) if x not in x_indice_to_remove], :]
grid = tmp[:, [y for y in range(grid.shape[1]) if y not in y_indice_to_remove]]

继续 Mr E,解决方案,然后填充结果也有效。

def pad_to_square(a, pad_value=np.nan):
m = a.reshape((a.shape[0], -1))
padded = pad_value * np.ones(2 * [max(m.shape)], dtype=m.dtype)
padded[0:m.shape[0], 0:m.shape[1]] = m
return padded

g = np.isnan(grid)
grid = pad_to_square(grid[:, ~np.all(g, axis=0)][~np.all(g, axis=1)])

另一种解决方案,建立在此处的其他答案之上。对于更大的矩阵,速度明显更快。

shape = grid.shape[0]

first_col = (i for i,col in enumerate(grid.T) if np.isfinite(col).any() == True).next()
last_col = (shape-i-1 for i,col in enumerate(grid.T[::-1]) if np.isfinite(col).any() == True).next()
first_row = (i for i,row in enumerate(grid) if np.isfinite(row).any() == True).next()
last_row = (shape-i-1 for i,row in enumerate(grid[::-1]) if np.isfinite(row).any() == True).next()

row_len = last_row - first_row
col_len = last_col - first_col
delta_len = row_len - col_len
if delta_len == 0:
pass
elif delta_len < 0:
first_row = first_row - abs(delta_len)
if first_row < 0:
delta_len = first_row
first_row = 0
last_row += abs(delta_len)
elif delta_len > 0:
first_col -= abs(delta_len)
if first_col < 0:
delta_len = first_col
first_col = 0
last_col += abs(delta_len)

grid = grid[first_row:last_row+1, first_col:last_col+1]

关于python - 裁剪矩阵的 nan 行和列,但保持正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20544272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com