从文本文件创建矩阵-python [英] Create a matrix from a text file - python
问题描述
我想从三列文件创建一个矩阵. 我敢肯定这非常容易,但是我只是不明白该怎么做.请保持温柔,我是python的初学者. 谢谢
I would like to create a matrix from a three column file. I am sure it's something extremely easy, but I just do not understand how it needs to be done. Please be gentle, I am a beginner to python. Thank you
我的输入文件的格式
A A 5
A B 4
A C 3
B B 2
B C 1
C C 0
所需的输出-完整的矩阵
Desired output - complete matrix
A B C
A 5 4 3
B 4 2 1
C 3 1 0
或-半矩阵
A B C
A 5 4 3
B 2 1
C 0
我尝试了这个,但是正如我所说,我对python和编程非常陌生.
I tried this, but as I said, I am VERY new to python and programming.
import numpy as np
for line in file('test').readlines():
name1, name2, value = line.strip().split('\t')
a = np.matrix([[name1], [name2], [value]])
print a
工作脚本-我的一位朋友也帮助了我,所以如果有人对简单的脚本感兴趣,就可以了.它不是最有效的,但是效果很好.
WORKING SCRIPT - One of my friend also helped me, so if anyone if interested in a simpler script, here it is. It's not the most efficient, but works perfectly.
data = {}
names = set([])
for line in file('test').readlines():
name1, name2, value = line.strip().split('\t')
data[(name1, name2)] = value
names.update([name1])
names = sorted(list(names))
print names
print data
output = open('out.txt', 'w')
output.write("\t%s\n" % ("\t".join(names)))
for nameA in names:
output.write("%s" % nameA)
for nameB in names:
key = (nameA, nameB)
if key in data:
output.write("\t%s" % data[(nameA, nameB)])
else:
output.write("\t")
output.write("\n")
output.close()
推荐答案
尝试:
import pandas as pd
import numpy as np
raw = []
with open('test.txt','r') as f:
for line in f:
raw.append(line.split())
data = pd.DataFrame(raw,columns = ['row','column','value'])
data_ind = data.set_index(['row','column']).unstack('column')
np.array(data_ind.values,dtype=float))
输出:
array([[ 5., 4., 3.],
[ nan, 2., 1.],
[ nan, nan, 0.]])
array([[ 5., 4., 3.],
[ nan, 2., 1.],
[ nan, nan, 0.]])
这篇关于从文本文件创建矩阵-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!