pandas 中事务矩阵的邻接矩阵
adjacency matrix from transaction matrix in pandas
我有一个交易数据框如下,其中索引是交易,列是产品。该数据的一小部分如下:
d_frame
Out[213]:
P1 P2 P3 P4
T1 1 1 0 1
T2 1 0 1 1
T3 1 0 1 0
T4 1 1 0 1
表示商品P1、P2、P4都在交易T1中一起购买过,以此类推。
现在我想从这个数据框创建邻接矩阵,它将每个共同购买的产品的数量加在一起。邻接矩阵如下:
d_adj
Out[214]:
P1 P2 P3 P4
P1 0 2 2 3
P2 2 0 0 2
P3 2 0 0 1
P4 3 2 1 0
矩阵显示P1和P2在交易T1和T4中一起购买,因此邻接矩阵中的P1P2和P2P1单元格应为2,依此类推
我想我可以从 Networkx 包中创建邻接关系并尝试了以下代码:
test = nx.from_pandas_adjacency(d_frame, create_using = nx.MultiGraph)
但出现了以下错误:
('Columns must match Indices.', "['T3', 'T1', 'T2', 'T4'] not in columns")
我也曾考虑过根据每笔交易中的产品排列创建边缘列表,但由于我的数据框很大,这不是一种有效的方法。
非常感谢任何帮助。
你可以按每一列分组,求和,然后连接它们。
import pandas as pd
d_frame = pd.DataFrame(data = [[1,1,0,1], [1,0,1,1] ,[1,0,1,0], [1,1,0,1]], index = ['T1', 'T2', 'T3', 'T4'], columns=['P1', 'P2', 'P3', 'P4'])
d_adj = pd.concat([d_frame.groupby(col).sum() for col in d_frame.columns]).loc[1] # loc[1] chooses the values where the column is 1
d_adj.fillna(0, inplace = True)
d_adj.index = d_adj.columns
Out[95]:
P1 P2 P3 P4
P1 0.0 2.0 2.0 3.0
P2 2.0 0.0 0.0 2.0
P3 2.0 0.0 0.0 1.0
P4 3.0 2.0 1.0 0.0
连接时,不要传递 sort = False
否则列将不对齐。
我有一个交易数据框如下,其中索引是交易,列是产品。该数据的一小部分如下:
d_frame
Out[213]:
P1 P2 P3 P4
T1 1 1 0 1
T2 1 0 1 1
T3 1 0 1 0
T4 1 1 0 1
表示商品P1、P2、P4都在交易T1中一起购买过,以此类推。 现在我想从这个数据框创建邻接矩阵,它将每个共同购买的产品的数量加在一起。邻接矩阵如下:
d_adj
Out[214]:
P1 P2 P3 P4
P1 0 2 2 3
P2 2 0 0 2
P3 2 0 0 1
P4 3 2 1 0
矩阵显示P1和P2在交易T1和T4中一起购买,因此邻接矩阵中的P1P2和P2P1单元格应为2,依此类推
我想我可以从 Networkx 包中创建邻接关系并尝试了以下代码:
test = nx.from_pandas_adjacency(d_frame, create_using = nx.MultiGraph)
但出现了以下错误:
('Columns must match Indices.', "['T3', 'T1', 'T2', 'T4'] not in columns")
我也曾考虑过根据每笔交易中的产品排列创建边缘列表,但由于我的数据框很大,这不是一种有效的方法。
非常感谢任何帮助。
你可以按每一列分组,求和,然后连接它们。
import pandas as pd
d_frame = pd.DataFrame(data = [[1,1,0,1], [1,0,1,1] ,[1,0,1,0], [1,1,0,1]], index = ['T1', 'T2', 'T3', 'T4'], columns=['P1', 'P2', 'P3', 'P4'])
d_adj = pd.concat([d_frame.groupby(col).sum() for col in d_frame.columns]).loc[1] # loc[1] chooses the values where the column is 1
d_adj.fillna(0, inplace = True)
d_adj.index = d_adj.columns
Out[95]:
P1 P2 P3 P4
P1 0.0 2.0 2.0 3.0
P2 2.0 0.0 0.0 2.0
P3 2.0 0.0 0.0 1.0
P4 3.0 2.0 1.0 0.0
连接时,不要传递 sort = False
否则列将不对齐。