首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Python中:创建一个表来可视化成对数据

在Python中:创建一个表来可视化成对数据
EN

Stack Overflow用户
提问于 2012-12-12 09:33:51
回答 2查看 620关注 0票数 1

我执行了一系列成对比较(准确地说是241x241)。

生成的文件如下所示:

代码语言:javascript
运行
复制
A,X,10
A,Y,20
X,Y,15

我想把它转换成一个表格,显示所有的成对比较。也就是说,像这样的东西

代码语言:javascript
运行
复制
,A,X,Y
A,,10,20
X,10,,15
Y,20,15,,

我甚至不知道如何开始解决这个问题。任何帮助,建议都将不胜感激!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-12 09:51:22

将配对数据存储到字典中:

代码语言:javascript
运行
复制
result_dict = {
    (A, X): 10,
    (A, Y): 20,
    (X, Y): 15,
}

和行/列标签:

代码语言:javascript
运行
复制
cols = sorted(set(a for a, b in result_dict.iterkeys()))
rows = sorted(set(b for a, b in result_dict.iterkeys()))

然后就是如何打印行了.

代码语言:javascript
运行
复制
for b in rows:
    row = list(result_dict.get((a, b), None) for a in cols)
    # print the row
票数 2
EN

Stack Overflow用户

发布于 2012-12-12 09:51:33

我有一种感觉,有更有效的方法,但你可以尝试一下这样的东西。它使用csv模块来加载/解析您的数据,然后也将其写回csv (假设您希望将输出放在一个文件中,也就是说,如果不是这样,可以对其进行调整):

代码语言:javascript
运行
复制
import csv
from collections import defaultdict

# Open the input file and read it all into a defaultdict
with open('table.csv', 'rb') as f:
  reader = csv.reader(f)

  # Dictionary to hold the nested values
  # This will be keyed by the letter ID, and each line of
  # the file will be written twice (so A,X,10 will be represented
  # as {'A': {'X': 10}, 'X': {'A': 10}}
  d = defaultdict(dict)
  for row in reader:
    d[row[0]][row[1]] = row[2]
    d[row[1]][row[0]] = row[2]

# Now we open the output file and write out our defaultdict
with open('t_out.csv', 'wb') as o:
  # Here our fieldnames will start with the 'empty' first header
  # and then be comprised of the keys of the dictionary (which
  # should contain all possible values for the table)
  fieldnames = [' '] + d.keys()
  writer = csv.DictWriter(o, fieldnames=fieldnames)

  # In Python 2.7, you can use writer.writeheaders()
  writer.writerow(dict((h, h) for h in fieldnames))

  # Now iterate through our dictionary, creating a row
  # dictionary that will contain the information to be written
  for k, v in d.iteritems():
    # Here we are putting the key in the 'empty' first column
    v[' '] = k
    writer.writerow(v)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13831400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档