NumPy构造新矩阵,去掉第i行第j列,保留行列索引
我有一个矩阵,大小是 m * n
(m 行 n 列)。在这个矩阵中,有一个位置是 (i,j)
,我想构建一个新的矩阵,大小是 (m-1)*(n-1)
,这个新矩阵要去掉包含这个位置的那一行和那一列,同时保留原来的索引。
举个例子,我的输入矩阵长这样:
1 2 3 4
1 a11 a12 a13- a14
2 a21- a22- a23* a24-
3 a31 a32 a33- a34
4 a41 a42 a43- a44
(在 a23
旁边的 * 表示这是给定的元素,旁边有横线的元素是要在输出中去掉的)
假设给定的 (i,j)
是 (2,3),我希望输出的结果是:
1 2 4
1 a11 a12 a14
3 a31 a32 a34
4 a41 a42 a44
这是我在 NumPy
中尝试的:
def myfunction(mymatrix=bipartite, row_idx=0, column_idx=0):
row_indices = range(mymatrix.shape[0])
row_indices.remove(row_idx)
column_indices = range(mymatrix.shape[1])
column_indices.remove(column_idx)
result = mymatrix[np.ix_(row_indices, column_indices)]
return result
print bipartite
print myfunction(bipartite, 2, 3)
[[1 0 1 0 0]
[1 0 0 1 0]
[0 1 0 1 0]
[0 1 0 0 1]
[0 0 1 0 1]]
[[1 0 1 0]
[1 0 0 0]
[0 1 0 1]
[0 0 1 1]]
但是在新矩阵中,我丢失了原来的行和列的索引。
有没有人能帮我解决这个问题?
或者说,我是不是根本走错了方向,因为在 Numpy
中矩阵不会保留行和列的名称,所以我必须使用 Pandas
中的 DataFrame
来模拟矩阵?
2 个回答
0
import numpy as np
def minor(arr, i, j):
# ith column, jth row removed
return arr[np.array(range(i)+range(i+1, arr.shape[0]))[:,np.newaxis],
np.array(range(j)+range(j+1,arr.shape[1]))]
arr = np.arange(16).reshape(4,4)
print(arr)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]]
print(minor(arr, 2, 3))
[[ 0 1 2]
[ 4 5 6]
[12 13 14]]
产生
1
如果你想保留一些索引信息,使用Pandas可能是最简单的办法。你可以在读取数组之后,删除相关的行或列。
比如说:
>>> M = np.random.rand((4, 4))
>>> df = pd.DataFrame(M)
>>> df
0 1 2 3
0 0.826425 0.888413 0.320257 0.079322
1 0.637170 0.144950 0.370768 0.967574
2 0.674793 0.995937 0.683142 0.403560
3 0.388024 0.619652 0.948890 0.088462
删除第 1
行和第 2
列:
>>> df.drop(1, axis=0).drop(2, axis=1)
0 1 3
0 0.826425 0.888413 0.079322
2 0.674793 0.995937 0.403560
3 0.388024 0.619652 0.088462