从python中的列表列表构造共现矩阵 [英] Construct co-occurrence matrix from a list of list in python

查看:62
本文介绍了从python中的列表列表构造共现矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有 n 个由一些值组成的列表.

Suppose we have n lists consisting of some values.

['a', 'b']
['b', 'c', 'd', 'e']
['a', 'd', 'e']
['b', 'e']

这里 n = 4.

这应该会产生一个像下面这样的数据帧

This should yield a dataframe like the below one

      'a'  'b'  'c'  'd'  'e'
'a'    0    1    0    1    1
'b'    1    0    1    1    2
'c'    0    1    0    1    1
'd'    1    1    1    0    2
'e'    1    2    1    2    0

推荐答案

这里有一个方法:

l1=['a', 'b']
l2=['b', 'c', 'd', 'e']
l3=['a', 'd', 'e']
l4=['b', 'e']

从列表中获取嵌套列表:

Get a nested list from the lists:

l = [i for i in [l1,l2,l3,l4]]

使用 itertools 获取每个列表中的所有组合.组合:

c = [list(itertools.combinations(i,2)) for i in l]
#[[('a', 'b')],
#[('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('d', 'e')],
#[('a', 'd'), ('a', 'e'), ('d', 'e')],
#[('b', 'e')]]

展平嵌套列表.请注意,每个元素都是使用 chain.from_iterable((i, i[::-1]) 以原始和相反顺序添加的.

Flatten the nested lists. Note that each element is added in original and reversed order using chain.from_iterable((i, i[::-1]).

a = list(chain.from_iterable((i, i[::-1]) for c_ in c for i in c_))

使用 pivot_table 并按 size 聚合以从结果生成共生矩阵

Use pivot_table and aggregate by size to generate a cooccurrence matrix from the result

df = pd.DataFrame(a)
pd.pivot_table(df, index=0, columns=1, aggfunc='size', fill_value=0)

1    a    b    c    d    e
0                         
a  0.0  1.0  0.0  1.0  1.0
b  1.0  0.0  1.0  1.0  2.0
c  0.0  1.0  0.0  1.0  1.0
d  1.0  1.0  1.0  0.0  2.0
e  1.0  2.0  1.0  2.0  0.0

这篇关于从python中的列表列表构造共现矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆