将邻接矩阵转换为向量
Convert adjacency matrix to vector
我想将邻接矩阵转换为向量。我已经想出了一个可行但似乎过于复杂的解决方案(使用 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
解决方法:
使用 np.triu_indices()
的对角线偏移参数 k
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])
我想将邻接矩阵转换为向量。我已经想出了一个可行但似乎过于复杂的解决方案(使用 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
解决方法:
使用 np.triu_indices()
k
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])