Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数据帧中的共现计数_Python_Pandas_Dataframe_Count - Fatal编程技术网

Python 数据帧中的共现计数

Python 数据帧中的共现计数,python,pandas,dataframe,count,Python,Pandas,Dataframe,Count,我有一个熊猫数据框,如下所示: tokens ----------- t1 t2 t3 t1 t2 t10 t10 t1 t1 t3 我只想将共现频率作为3个单独的列: token1 token2 count t1 t1 2 t1 t2 1 t1 t3 4 t2 t3 1 t2 t10 2 t10 t10 1 这可能会应用于一个巨大的数据集,因此任何关

我有一个熊猫数据框,如下所示:

tokens
-----------
t1 t2 t3 t1
t2 t10 t10
t1 t1 t3
我只想将共现频率作为3个单独的列:

token1  token2  count
  t1      t1      2
  t1      t2      1
  t1      t3      4
  t2      t3      1
  t2     t10      2
 t10     t10      1

这可能会应用于一个巨大的数据集,因此任何关于速度/性能的建议都会受到欢迎。

为每个分割的值创建两个值的组合,将其展平,使用
计数器进行排序和计数,最后创建元组并传递给
数据帧
构造函数:

from collections import Counter
from  itertools import combinations
L = [(*k, v) for k, v in Counter([tuple(sorted(y)) for x in df['tokens'] 
             for y in combinations(x.split(), 2)]).items()]

df = pd.DataFrame(L, columns=['token1','token2','count'])
print (df)
  token1 token2  count
0     t1     t2      2
1     t1     t3      4
2     t1     t1      2
3     t2     t3      1
4    t10     t2      2
5    t10    t10      1

非常感谢你!