首页 > 解决方案 > Python 3 一起收集表格

问题描述

我有多个看起来都一样的表。它们的格式为

|时间|SF|COL3|COL4|COL5|

表中的所有数据都是浮点数,仅由空格分隔。所有表都有相同的 TIME 列,COL3、COL4 和 COL5 的值没有用处。我想做的是用数据创建一个新文件

|TIME|SF_1|SF_2|SF_3|...|SF_N|

所以我需要代码来处理 N 个表(所有格式都相同)。

到目前为止,我已经完成了:

files = (np.loadtxt('files.txt', dtype=str, unpack=True))
i=0
while i<len(files):
    if i == 0:
        readfile = np.loadtxt(files[i], dtype=str, unpack=True, usecols=range(0,3))
        time=readfile[0]
        print(time)
        globals()["SF_"+str(i)]=readfile[1]
    else:
        readfile = np.loadtxt(files[i], dtype=str, unpack=False, usecols=1)
        globals()["SF_"+str(i)] = readfile

(其中files.txt是所有表名的列表)。

所以这给了我列表 TIME,然后是变量 SF_1、SF_2、SF_3 等,尽管它以一种不雅的方式这样做。但是现在我不知道如何将它作为单独的列而不是行输出到数据文件中。任何建议都将不胜感激,包括如何改进我以前的代码,因为我非常清楚它是不明智的。

标签: python-3.xtext-files

解决方案


我设法用以下代码解决了这个问题

files = np.loadtxt('files.txt', dtype=str, unpack=True)
i=0
while i<len(files):
    if i==0:
        readfile = np.loadtxt(files[i], dtype=float, unpack=True, usecols=range(0,3))
        time = readfile[0] #although for only the first file it also extracts time
        SF = readfile[1]
        out_table = np.vstack((time, SF))
    else:
        readfile = np.loadtxt(files[i], dtype=float, unpack=False, usecols=1)
        SF = np.array(readfile)
        out_table = np.vstack((out_table, SF))
    i+=1
out_table = out_table.T

#Creates the Header line of column names for easy importing into TOPCAT
n=1
header = '#BJD '
while n < len(out_table[0]):
    header = header + 'SF_'+str(n)+' '
    n += 1
output.write(header+"MEDSF\n")

#Prints each row into the output file line by line
j=0
while j<len(out_table):
    output.write(" ".join(map(str, out_table[j]))+" "+str(np.median(out_table[j]))+"\n")
    j+=1

output.close()

推荐阅读