Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.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 - Fatal编程技术网

Python 基于数据帧的加权对列表

Python 基于数据帧的加权对列表,python,pandas,Python,Pandas,我有这样一个熊猫数据框: doc type thing 3 A pig 4 B horse 4 C cat 4 D pig 5 C horse 5 A bird 5 B cat doc thing_x thing_y 5 4 horse pig 6 4 cat horse 8 4 cat horse 10 4 cat pig 15 4 horse pig 1

我有这样一个熊猫数据框:

doc type    thing
3   A   pig
4   B   horse
4   C   cat
4   D   pig
5   C   horse
5   A   bird
5   B   cat
    doc thing_x thing_y
5   4   horse   pig
6   4   cat     horse
8   4   cat     horse
10  4   cat     pig
15  4   horse   pig
16  4   cat     horse
18  4   cat     horse
20  4   cat     pig
29  5   bird    horse
31  5   bird    cat
32  5   cat     horse
我想要一个新的三列数据框;事情由曾经出现在同一个“文档”中的所有“事物”对填充的时间,以及在多少个文档中。根据上述数据帧,所需输出为:

thing   thing   times
horse   cat     2
horse   pig     1
cat pig         1
horse   bird    1
bird    cat     1
在熊猫之外,我通过itertools取得了一些成就,但如何利用熊猫做到这一点呢?

一个可能的解决方案:

df_filtered = df[['doc', 'thing']]
pd.merge(df_filtered, df_filtered, on='doc')
    .query("thing_x < thing_y")
    .groupby(by=['thing_x', 'thing_y'])
    .agg({'doc': 'nunique'})
    .reset_index()
然后,您可以完成这两件事,计算每个组的不同文档的数量,并调用以展平分层分组

最终结果:

    thing_x thing_y doc
0   bird    cat     1
1   bird    horse   1
2   cat     horse   2
3   cat     pig     1
4   horse   pig     1

好建议。“文档”列中的数字在您的最终结果中实际表示了什么?对于每两件事,数字是这两件事在同一文档中出现的次数。是的,我现在看到了。我意识到可以添加代码来删除thing_x==thing_y的行。还有一个简单的方法来计算线,如马;猫和猫;马只有一次,所以方向x-y,y-x不重要?我已经编辑了我的答案。首先,我意识到你想要的是这对夫妇出现在一起的不同文档的数量,而不是他们在同一文档中出现的次数。我删除了thing_x==thing_y条目并修复了方向问题。这很好。非常感谢。只是出于兴趣,你到底做了什么。询问你做什么,什么时候