填充在python(numpy的)阵列? [英] Populate arrays in python (numpy)?

查看:307
本文介绍了填充在python(numpy的)阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于下面的格式的文件:

  A 0
A B 1
一个C 1
B B 0
B A 1
B C 1
C C 0
c进行1
C B 1

第三列是在第一和第二列中的项之间的距离。如果我读这样的文件到pyton为嵌套表,我怎么把它转换为一个对称矩阵,即,

  A B C
一个0 1 1
B 1 0 1
b 1分配1 0

?我还要包括列和行名称。

我想preferably喜欢用numpy的来完成这个任务。

有什么建议?

谢谢,
D.


解决方案

 导入numpy的是NP
从进口和itertools计数数据= [line.split()在inputfile.readlines线()]
行=字典(邮政编码(排序(集(行[0],在数据线)),计数()))
COLS =字典(邮政编码(排序(集(行[1]在数据线)),计数()))
阵列= np.zeros((LEN(行),LEN(COLS)))对于行,列,VAL数据:
    指数=(行[行] COLS [COL])
    数组[索引] = VAL

我不知道如何标记在numpy的行和列,所以我只是做了一个字典映射行标签的行索引,另一个做了列相同。如果你需要它,你可以做一个反向映射,如下,也可以使行列数一的 BIDICT

  rows_reverse =字典((V,K)为K,V行)
cols_reverse =字典((V,K)为K,V在COLS)

Given a file in the format below:

a a 0
a b 1
a c 1
b b 0
b a 1
b c 1
c c 0
c a 1
c b 1

The third column is the distance between the items in the first and second columns. If I read such a file into pyton as a nested list, how do I convert it to a symmetrical matrix, i.e.,

  a b c
a 0 1 1
b 1 0 1
b 1 1 0

? I also wish to include the column and row names.

I would preferably like to use numpy to complete this task.

Any suggestions?

Thanks, D.

解决方案

import numpy as np
from itertools import count

data = [line.split() for line in inputfile.readlines()]
rows = dict(zip(sorted(set(line[0] for line in data)), count()))
cols = dict(zip(sorted(set(line[1] for line in data)), count()))
array = np.zeros((len(rows), len(cols)))

for row, col, val in data:
    index = (rows[row], cols[col])
    array[index] = val

I don't know how to label rows and columns in numpy, so I just made a dict mapping the row label to the row index and another doing the same for the columns. If you need it you can make a reverse map, as below, or you can make rows and cols a bidict.

rows_reverse = dict((v, k) for k, v in rows)
cols_reverse = dict((v, k) for k, v in cols)

这篇关于填充在python(numpy的)阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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