gpt4 book ai didi

python - 移动 numpy 数组列和行?

转载 作者:行者123 更新时间:2023-11-28 22:18:15 24 4
gpt4 key购买 nike

我有这样的 numpy 数组,其中有一列和一行零:

 ([[0. , 2.8, 3.5, 0. , 2.5, 1. , 0.8],
[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[3.5, 2.5, 0. , 0. , 2.8, 1.3, 1.1],
[3.6, 3.8, 3.3, 0. , 2.5, 0.6, 0.4],
[2.5, 1.5, 2.8, 0. , 0. , 3.1, 1.9],
[1. , 0.8, 1.3, 0. , 3.1, 0. , 2.8],
[0.8, 1.6, 1.1, 0. , 1.9, 2.8, 0. ]])

我想将零行移到顶部,将零列移到左侧或将其删除:

 ([[0. , 0. , 0. , 0. , 0. , 0. ]
[0. , 2.8, 3.5, 2.5, 1. , 0.8],
[3.5, 2.5, 0. , 2.8, 1.3, 1.1],
[3.6, 3.8, 3.3, 2.5, 0.6, 0.4],
[2.5, 1.5, 2.8, 0. , 3.1, 1.9],
[1. , 0.8, 1.3, 3.1, 0. , 2.8],
[0.8, 1.6, 1.1, 1.9, 2.8, 0. ]])

有什么快速简便的方法吗?顺便说一句,我知道列号和行号,所以我不必搜索它。

最佳答案

同时删除列和行,然后重新添加一行零。

这适用于您的示例:

import numpy as np
a = np.array([[0. , 2.8, 3.5, 0. , 2.5, 1. , 0.8],
[0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[3.5, 2.5, 0. , 0. , 2.8, 1.3, 1.1],
[3.6, 3.8, 3.3, 0. , 2.5, 0.6, 0.4],
[2.5, 1.5, 2.8, 0. , 0. , 3.1, 1.9],
[1. , 0.8, 1.3, 0. , 3.1, 0. , 2.8],
[0.8, 1.6, 1.1, 0. , 1.9, 2.8, 0. ]])

def remove_column_of_zeros_and_shift_row(a, row, col):
without_row = np.delete(a, row, axis=0)
without_row_and_col = np.delete(without_row, col, axis=1)
z = np.zeros((1, len(without_row_and_col[0])))
without_col_shifted_row = np.append(z, without_row_and_col, axis=0)
return without_col_shifted_row

my_result = remove_column_of_zeros_and_shift_row(a, 1, 3)

关于python - 移动 numpy 数组列和行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50653035/

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