2014-12-21 3 views
0

이상한 방법으로 배치 된 140 세트의 데이터 세트가 3 개 있습니다. 파이썬으로 재 배열하는 방법을 알 수 없습니다. 파일은 위에 4 행, 4 행에 5 행으로 정렬됩니다. 헤더가없고 행 1과 2는 하나의 열, 행 3은 2 개의 열, 행 4는 가비지입니다. 처음 세 행은 데이터 세트의 식별자입니다. 각 데이터 세트에는 여러 레코드가 있습니다. 예 :잘못된 데이터 세트 레이아웃

xx4 <--ID 
070414 <--DateStrong 
5.6 10 <--Force Ratio 
Sample Rate: 50/s <--Garbage 


220.68 0.14 17.80 92.20 
220.80 0.02 9.40 9.40 
224.32 0.14 14.60 72.20 
227.08 0.14 26.60 130.60 
227.78 0.08 19.60 62.00 
228.04 0.18 40.40 257.20 
231.22 0.12 14.00 61.20 

내가 할 세트를 마련하기 위해 노력하고있어 :

xx4, 070414, 5.6, 10, 220.68, 0.14, 17.80, 92.20 
xx4, 070414, 5.6, 10, 220.80, 0.02, 9.40, 9.40 
xx4, 070414, 5.6, 10, 224.32, 0.14, 14.60, 72.20 

내 현재 작업 코드는 다음과 같습니다

import os 
import sys 
import csv 
import pandas as pd 
import numpy as np 
import itertools as it 
import benFuncts.BenFuncts as bf #My own functions 
import matplotlib.pyplot as plt 

ID = [] 

ID_dict = {} 
DATE = [] 
FORCE = [] 
RATIO = [] 

TIME = [] 
DURR = [] 
pF = [] 
TOF = [] 

ED7 = [] 
ED6 = [] 
ED5 = [] 
ED4 = [] 

h = 'DATE', 'DAYNUM', 'RATIO', 'CRIT', 'TOTRESP', 'CRITRESP', 'PELLETS', 'AVG_PF', 'AVG_TOF' 

Crit = {} 


MastList = [] 
rd_files = [] # List of file strings 


# Makes the main file path in this case: 
# /Users/benlibman/Desktop/EffortDemandTests/EffortDemandPyTests/ 
path = str(os.getcwd()) + '/' 

# List of files in the working directory (see path above) 
mainDir = os.listdir(str(os.getcwd()) + '/') 

# Pulls the list files from the mainDir (above) 
ID = [i for i in mainDir if len(i) <= 3 and 'ED' in i] 

# f_Out = csv.writer(open('MainFile', 'wa'), delimiter=',') 
# f_Out = open('MainFile', 'wa') 
# , quoting=csv.QUOTE_NONE) 
f_In = csv.reader(open('ED7', 'rb'), delimiter='\t') 


def mkPath(): 
    for row in f_In: 
     for i in row: 
      if len(i) > 1: 
       rd_files.append(path + str(i)) 

mP = mkPath() 


# pdmF = pd.read_csv('MainFile', sep='\t', engine='python') 
# with open('ED7120214', 'r') as f: 


df = pd.read_csv(open('ED7120214', 'r'), sep='\t', skiprows=5, usecols=(
    0, 1, 2, 3), names=('TIME', 'DURR', 'pF', 'TOF')) 

frCR = pd.read_csv(open('ED7120214', 'r'), sep=' ', skiprows=(0, 1, 3), skipfooter=(
    len(df)), engine='python', index_col=False, names=('FORCE', 'RATIO')) 

date_index = pd.read_csv(open('ED7120214', 'r'), squeeze=True, sep=' ', skiprows=(
    0, 2, 3), skipfooter=(len(df)), engine='python', index_col=False, names=('DATE', 'NaN')) 

id_index = pd.read_csv(open('ED7120214', 'r'), squeeze=True, sep=' ', skiprows=(
    1, 2, 3), skipfooter=(len(df)), engine='python', index_col=False, names=('ID', 'NaN')) 


pDF = pd.DataFrame(df) 

for row in pDF.TIME: 
    TIME.append(row) 

for row in pDF.DURR: 
    DURR.append(row) 

for row in pDF.pF: 
    pF.append(row) 

for row in pDF.TOF: 
    TOF.append(row) 

print pDF.pF.mean() 

FORCE.append(frCR.FORCE) 
RATIO.append(frCR.RATIO) 

DATE.append(list(date_index.DATE)) 
ID_dict.update(id_index.ID) 

DATE = [str(i).strip('[]') for i in DATE] 

# ED7.append(FORCE) 
# ED7.append(DATE) 
# ED7.append(RATIO) 
ED7.append(TIME) 
ED7.append(DURR) 
ED7.append(pF) 
ED7.append(TOF) 

Dt = bf.addCol(range(len(TIME)), DATE) 


with open('MainFile', 'wa') as mf: 
    pDF.to_csv(mf, header=True, index_names=True, names=(
     'DATE', 'DAYNUM', 'TIME', 'DURR', 'pF', 'TOF')) 
+2

* 캡처 한 다음 재배치 할 수있는 패턴을 식별하는 데 문제가 있습니까? 아니면 코드를 알아 냈습니까?하지만 코드가 작동하지 않습니다. 코드를 게시하고 문제가 무엇인지, 그리고 문제를 해결하기 위해 이미 시도한 사항을 설명해야합니다. 그러면 코드를 수정하지 않아도됩니다. 파일 당 하나 이상의 * 레코드 *가 있습니까? – wwii

+0

답장을 보내 주셔서 감사합니다. 죄송합니다. 일반적인 cols 및 행 형식으로 패턴을 재정렬하는 데 문제가 있습니다. 각 파일에는 22,000 개 이상의 행이 있습니다. – AtomicBen

+0

원하는 형식으로 파일에 데이터를 다시 쓰는 최종 목표는 무엇입니까? – wwii

답변

0

당신이하려고하는 모든 포맷 인 경우 데이터를 다시 작성하여 파일에 다시 작성하면 다음 예에서 파일 형식으로 작동합니다.

with open('data.txt') as in_file, open('new.txt', 'w') as out_file: 
    # get the dataset identifiers 
    ID = in_file.next().strip() 
    date_strong = in_file.next().strip() 
    force_ratio = in_file.next().strip() 
    force_ratio1, force_ratio2 = force_ratio.split() 
    in_file.next() # Garbage line 
    # example data has two blank lines 
    in_file.next() 
    in_file.next() 
    dataset_id = (ID, date_strong, force_ratio1, force_ratio2) 
    # iterate over the records 
    for line in in_file: 
     # prepend the dataset id 
     record = list(dataset_id) 
     record.extend(line.split()) 
     # write to the new file 
     out_file.write(','.join(record) + '\n')