我想将邻接矩阵转换为向量。我已经想出了一个可行的解决方案,但似乎过于复杂(使用 Pandas 的解决方法)。必须有更简单的方法来做到这一点?
例子:
import numpy as np
import pandas as pd
A = np.array([[0,1,2,3],
[1,0,1,0],
[2,1,0,0],
[3,0,0,0]],
dtype=float)
il = np.tril_indices(len(A))
A[il] = np.nan
A_df = pd.DataFrame(A)
A_stacked = A_df.stack().reset_index()
A_vector = A_stacked[0]
这给了你:
0 1.0
1 2.0
2 3.0
3 1.0
4 0.0
5 0.0
Name: 0, dtype: float64
解决方案:用斜offset参数k
的np.triu_indices()
import numpy as np
import pandas as pd
A = np.array([[0,1,2,3],
[1,0,1,0],
[2,1,0,0],
[3,0,0,0]],
dtype=float)
iu = np.triu_indices(len(A),k=1)
A[iu]
结果是
array([1, 2, 3, 1, 0, 0])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句