2013-11-28 2 views
0

많은 양의 데이터, 22 열 및 10000 행을 가진 CSV 파일이 있습니다. 첫 번째 행은 titles이고 다른 모든 행은 데이터입니다. 파일에서 읽습니다. (그냥 읽으면 원본 파일을 변경하고 싶지 않습니다.) 이제 제목 수 옆에있는 열 수를 줄이고 3 열만 저장하려고합니다. COLS의 순서는, 파일의 파일에서 변경 될 수 있습니다 때로는 "LUX"(COL)는 COL 번호 5에있을 것입니다, 때로는 COL 번호 20, 8, 등등에 .. 지금까지 나는이있어 :파이썬에서 행렬 열을 줄이는 방법은 무엇입니까?

with open('test.csv', 'rb') as csvfile: 
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # open the csv file 

medianGoodPixels = [] #vector to pixels 
Lux = [] #vector to LUX 
sdVer = [] # vector to the version 
NewCsvTable = [] #will be a matrix with 3 cols, LUX, pixels, and version 

for row in spamreader: 
    if row == "LUX": 
     #Here I'm stuck 

나는이 행이 각 반복에서 모든 행을 두 번째 반복에서 실제로 제공한다는 것을 깨달았습니다. 두 번째 행의 데이터 일뿐입니다. 어떻게 든 2 개의 루프를 사용해야 겠지만 정확하게는 모르겠습니다.

감사합니다.

답변

1

헤더 행에 list.index을 사용하면 다양한 헤더의 색인을 찾을 수 있습니다.

with open('test.csv', 'rb') as csvfile: 
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # open the csv file 
    medianGoodPixels = [] #vector to pixels 
    Lux = [] #vector to LUX 
    sdVer = [] # vector to the version 
    NewCsvTable = [] #will be a matrix with 3 cols, LUX, pixels, and version 
    header = next(spamreader) #Returns the header 
    lux_col, pixel_col, version_col = header.index('LUX'), header.index('pixel'),\ 
             header.index('version') 

    #Now iterate over rest of the rows. 
    for row in spamreader: 
     Lux.append(row[lux_col]) 
     sdVer.append(row[version_col]) 
     medianGoodPixels.append(row[pixel_col]) 
+0

hcwhsa 은 많은 사람을 감사합니다! 필요한 것! – shlomi

0

이은 행 당 하나 개의 사전을 반환 확실히 콜 럼 이름이 무엇인지 알아 내기 위해 문서의 첫 번째 행을 사용하여 전문 csv 모듈 클래스 csv.DictReader위한 작품입니다.

예 :

Lux, sdVer, medianGoodPixels = [], [], [] 
with open('test.csv', 'rb') as csvfile: 
    csv_reader = csv.DictReader(csvfile, delimiter=',', quotechar='|') 
    for dict_row in csv_reader: 
     Lux.append(dict_row['LUX']) 
     sdVer.append(dict_row['version']) 
     medianGoodPixel.append(dict_row['pixel']) 
관련 문제