python - 如何在 python 中为多个数据帧形成矩阵或表格(重叠计数)

标签 python

我遇到了一个需要用python解决的问题。

dataframe 1 dataframe 2             dataframe 3 
SID UID     SID UID                  SID    UID
123 dog     456 dog                  789    monkey
123 cat     456 bat                  789    fox
123 fish    456 bird                 789    bird
123 horse   456 cat                  789    donkey
123 mouse   456 mouse                789    mouse
123 cow     456 fox                  789    cat

我已经尝试过数据帧的交集,但它只适用于 2 个数据帧。我总共有 26 个数据帧,但例如我只使用了 3 个数据帧。

输出可以是 DF1 与 DF2 和 DF3 重叠的表格(类似于 DF2 与 DF1 和 DF3)或如下所示的矩阵:

    123 456 789
123 6   3   2
456 3   6   4
789 2   4   6

最佳答案

这是一个如何打印包含所有交点的矩阵的简单示例:

dfs = {'123': {'dog', 'cat', 'fish', 'horse', 'mouse', 'cow'},
       '456': {'dog', 'bat', 'bird', 'cat', 'mouse', 'fox'},
       '789': {'monkey', 'fox', 'bird', 'donkey', 'mouse', 'cat'}}

def matrix(dfs):
  print (' '*4 + ' '.join(dfs.keys()))
  for x in dfs.keys():
    print (x, end=' ')
    for y in dfs.keys():
      print('{:>3}'.format(len( dfs[x] & dfs[y] )), end=' ')
    print('')

matrix(dfs)

但是你应该通过使用组合来避免冗余计算(所有的一切):

import itertools

dfs = {'123': {'dog', 'cat', 'fish', 'horse', 'mouse', 'cow'},
       '456': {'dog', 'bat', 'bird', 'cat', 'mouse', 'fox'},
       '789': {'monkey', 'fox', 'bird', 'donkey', 'mouse', 'cat'}}

for x, y in itertools.combinations(dfs.keys(), 2):
  print('{} & {}: {}'.format(x, y, len( dfs[x] & dfs[y] )))

这将只计算独特的对:

123 & 456: 3
123 & 789: 2
456 & 789: 4

关于python - 如何在 python 中为多个数据帧形成矩阵或表格(重叠计数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56753031/

相关文章:

Python/Django : What does this line do?

python - 更改 plt.plot 的 for 循环中的标题并创建 6x16 子图

python - Python 寻址 CSV 文件中 Linux 和 Windows 的区别

python - 在 Cygwin/Python2.7 中安装包时出现 pip 错误

python - 打印不带文件扩展名的 __file__

python - 从子类访问 python @property 的值

python - Pandas DataFrame : Unusual Behaviour with json. 转储(额外的双引号)

python - 使用 OpenPyXL 导入多个 Excel 文件

python - 构建列表

python - 如何在 Django 中添加访客(匿名)用户的新记录