如何在Linux上用Python对该表进行排序

2024-05-16 05:52:17 发布

您现在位置:Python中文网/ 问答频道 /正文

import sys, subprocess, glob

mdbfiles = glob.glob('*.res')
for DATABASE in mdbfiles: 

    subprocess.call(["mdb-schema", DATABASE, "mysql"])

    table_names = subprocess.Popen(["mdb-tables", "-1", DATABASE],
                                   stdout=subprocess.PIPE).communicate()[0]
    tables = table_names.splitlines()

    sys.stdout.flush()

    a=str('Channel_Normal_Table')

    for table in tables:
        if table != '' and table==a:

            filename = DATABASE.replace(".res","") + ".csv"
            file = open(filename, 'w')
            print("Dumping " + table)
            contents = subprocess.Popen(["mdb-export", DATABASE, table],
                                        stdout=subprocess.PIPE).communicate()[0]

            # I NEED TO PUT SOMETHING HERE TO SORT AND EXTRACT THE DATA I NEED


            file.write(contents)
            file.close()

我从数据库中提取了一个表。我们称之为table。我需要执行以下操作,但有点卡住了:

^{pr2}$
  1. 提取每个循环的最后一行(最新的一行),或者更高级地对循环进行排序 按时间,并提取具有最新时间的循环行。作为 你可以看到,最后一行并不总是有最新的时间 我们的试验机出故障了,但通常是这样。但是越大 时间越晚编号。在
  2. 提取最后五个周期的所有行
  3. 提取循环4到周期30的所有行。在

我尝试了各种方法,比如根据我有限的Python知识创建和排序字典和列表,但是没有一种方法得到所需的输出。这简直让我发疯了。谢谢!在


Tags: infortablesnamesstdoutsys时间table
3条回答

使用pandaspymdb可以轻松完成工作

使用pandas,您可以毫不费力地处理时间序列数据。 看看吧熊猫数据帧. 这就是你所需要的。在

首先,让我们读取该文件并将找到的值转换为循环列的整数,其余的值为浮点:

databyrow=[]
with open('/tmp/temps.txt', 'r') as f:
    header=f.readline().strip().split()
    for line in f:
        temp=[]
        for i,val in enumerate(line.strip().split()):
            fn=int if i==0 else float
            try:
                val=fn(val)
            except ValueError:
                print val,'not converted'
            temp.append(val)    
        databyrow.append(temp)                
print databyrow  

印刷品:

^{pr2}$

现在,您可以根据刚刚创建的列表列表中的循环列列表创建组字典:

^{3}$

印刷品:

{1: [[1, 0.078, 0.0, 0.121], [1, 30.1, 0.0, 0.119], [1, 60.2, 0.0, 0.117]], 
 2: [[2, 90.2, 0.0, 0.114], [2, 120.0, 0.0, 0.111], [2, 150.0, 0.0, 0.108], [2, 180.0, 0.0, 0.105], [2, 210.0, 0.0, 0.102]], 
 3: [[3, 240.0, 0.0, 0.0993], [3, 270.0, 0.0, 0.0966], [3, 300.0, 0.0, 0.0938], [3, 310.0, 0.4, 1.26]]}

现在您可以直接获得每个周期的最后N行:

>>> N=2
>>> data_bycycle[1][-N:]
[[1, 30.1, 0.0, 0.119], [1, 60.2, 0.0, 0.117]]    

如果要按最新时间对其中一个组进行排序:

>>> sorted(data_bycycle[2],key=lambda li: li[1])[-1]
[2, 210.0, 0.0, 0.102]  

编辑

下载链接的dropbox文件时,您的csv文件不是空格分隔的。在

以下是如何阅读这样的内容:

import csv

databyrow=[]
with open('/tmp/VC0307a.csv', 'r') as f:      # potentially you can use 'contents' here
    for i,row in enumerate(csv.reader(f)):
        if i==0:
            header=row
        else:
            temp=[]
            for j,val in enumerate(row):
                fn=int if j in (0,1) else float
                try:
                    val=fn(val)
                except ValueError:
                    print val, 'not converted'
                temp.append(val)     
            databyrow.append(temp)

在内存中保存后,可以按特定的数字列进行排序:

^{8}$

这并不难,但你必须一步一步来:

from collections import defaultdict

table = """\
Cycle Test_Time  Current    Voltage
1     7.80E-002 0.00E+000   1.21E-001
1     3.01E+001 0.00E+000   1.19E-001
1     6.02E+001 0.00E+000   1.17E-001
2     9.02E+001 0.00E+000   1.14E-001
2     1.20E+002 0.00E+000   1.11E-001
2     1.50E+002 0.00E+000   1.08E-001
2     1.80E+002 0.00E+000   1.05E-001
2     2.10E+002 0.00E+000   1.02E-001
3     2.40E+002 0.00E+000   9.93E-002
3     2.70E+002 0.00E+000   9.66E-002
3     3.00E+002 0.00E+000   9.38E-002
3     3.10E+002 4.00E-001   1.26E+000"""

# Split into rows
table = table.splitlines()

# Split each row into values
table = [row.split() for row in table]

# Associate the column names with their index
headers = table.pop(0)
H = {x: i for i, x in enumerate(headers)}
time_index = H["Test_Time"]
cycle_index = H["Cycle"]

# Sort by Test_Time
table.sort(key=lambda row: float(row[time_index]))

# Associate each test with its cycle
D = defaultdict(list)
for row in table:
  D[int(row[cycle_index])].append(row)

# Present the information
print(*headers, sep='\t')
print("Latest row for each cycle")
for cycle in sorted(D.keys()):
  tests = D[cycle]
  latest_test = tests[-1]
  print(*latest_test, sep='\t')

print("All rows for last 5 cycles")
for cycle in sorted(D.keys())[-5:]:
  tests = D[cycle]
  for test in tests:
    print(*test, sep='\t')

print("All rows for cycles 4 through 30")
for cycle in sorted(D.keys()):
    if 4 <= cycle <= 30:
      tests = D[cycle]
      for test in tests:
        print(*test, sep='\t')

相关问题 更多 >