[英]Create a direct edge matrix from edge list
Sample data:样本数据:
data = {
'node1': [1, 1,1, 2,2,5],
'node2': [8,16,22,5,25,10],
'weight': [1,1,1,1,1], }
df = pd.DataFrame(data, columns = ['node1','node2','weight'])
The given data is edge list with first column indicating the node 1
and the second column shows the node which is directly connected to the first node.给定的数据是边列表,第一列表示
node 1
,第二列表示直接连接到第一个节点的节点。 Given is a edge list with column 1
as node1
, column 2
as node2
and weight.给定的是一个边列表,第
column 1
作为node1
,第column 2
作为node2
和权重。 I want to create a matrix with each row representing all the direct edges there are for a given node.我想创建一个矩阵,每一行代表给定节点的所有直接边。 (Each row is a node and the columns in it are the direct edges for the given node) using Pandas Dataframe.
(每一行是一个节点,其中的列是给定节点的直接边)使用 Pandas Dataframe。
output:输出:
8 16 22
5 25 0
0 0 0
0 0 0
10 0 0
IIUC国际大学联盟
df=df.assign(Cu=df.groupby('node1').cumcount()).set_index('Cu').groupby('node1').apply(lambda x : x['node2']*x['weight']).unstack('Cu').fillna(0)
df
Out[71]:
Cu 0 1 2
node1
1 8.0 16.0 22.0
2 5.0 25.0 0.0
5 10.0 0.0 0.0
For getting you out put , you can reindex
+ fillna
为了让你摆脱困境,你可以
reindex
+ fillna
Edit: Notice your expected output contian some all 0 row,编辑:注意你的预期输出 contian 一些全 0 行,
df.reindex([1,2,3,4,5]).fillna(0)
Out[107]:
Cu 0 1 2
node1
1 8.0 16.0 22.0
2 5.0 25.0 0.0
3 0.0 0.0 0.0
4 0.0 0.0 0.0
5 10.0 0.0 0.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.