2017-12-07 1 views
0

저는 파이썬에 대해 매우 익숙해 져있어서 제발 참아주십시오. 다음과 같은 CSV 파일이 있습니다 :CSV 파일의 고유 한 개인을 새 파일로 복사하는 방법

Animal Locations.

파일을 반복하려고하고 있으며 모든 고유 한 개인마다 새 CSV 파일을 만들고 행을 복사합니다. 한 동물에 대해이 작업을 성공적으로 수행했지만 좀 더 일반적인 접근법에 대한 구문을 만드는 데 문제가 있습니다. 여기에 내가 현재 가지고있는 것입니다 :

import arcpy 
import csv 
from csv import DictReader 

WS = arcpy.env.workspace = raw_input("Where if your workspace") 
infile = raw_input("where is your file?") 
outfile = raw_input("What is your outfile name?") 
arcpy.env.overwriteOutput = True 


with open(infile, "r") as csvFile, open(outfile, "w") as out, open("outfile2.csv", "w") as out2: 
    reader = csv.DictReader(csvFile) 
    writer = csv.writer(out) 
    writer.writerow(reader.fieldnames) 
    for row in reader: 
     if row["Animal"] == "1": 
      values = [row[field] for field in reader.fieldnames] 
      writer.writerow(values) 

답변

1

가 자신의 CSV 파일로 각 Animal를 작성하려면, 당신은 동물의 종류마다 다른 파일을 열어야합니다. 이것은 사전을 사용하여 파일 객체와 각 동물에 대한 csv 작성기 객체를 저장함으로써 수행 할 수 있습니다. 마지막에,이 다음 제대로 모든 파일을 닫고하는 데 사용할 수 있습니다 :

import csv 

output_csvs = {} # e.g. {'1' : [file_object, csv_object]} 

with open('input.csv', 'rb') as f_input: 
    csv_reader = csv.reader(f_input) 
    header = next(csv_reader) 

    for row in csv_reader: 
     animal = row[0] 

     if animal in output_csvs: 
      output_csvs[animal][1].writerow(row) 
     else: 
      f_output = open('animal_{}.csv'.format(animal), 'wb') 
      csv_output = csv.writer(f_output) 
      output_csvs[animal] = [f_output, csv_output] 
      csv_output.writerow(header) 
      csv_output.writerow(row) 

for csv_file, csv_writer in output_csvs.values(): 
    csv_file.close() 

이는 동물에 따라 당신의 이름 출력 CSV 파일의 집합을 줄 것, 예를 들어,

from itertools import groupby 
import csv 

with open('input.csv', 'rb') as f_input: 
    csv_reader = csv.reader(f_input) 
    header = next(csv_reader) 

    for animal, group in groupby(sorted(csv_reader), lambda x: x[0]): 
     with open('animal_{}.csv'.format(animal), 'wb') as f_output: 
      csv_output = csv.writer(f_output) 
      csv_output.writerow(header) 
      csv_output.writerows(group) 

상기 데이터를 메모리에 판독 할 수있을만큼 작은 경우 animal_1.csv


달리, 그것은 파이썬 itertools.groupby() 기능을 이용하여 한번에 동물 출력 한 블록으로 분류 될 수있다 sorted()을 사용하면 같은 종류의 모든 동물을 함께 그룹화 할 수 있습니다. 이것이 이미 데이터에있는 경우 정렬이 필요하지 않습니다.


당신이 glob.glob()을 사용할 수 이러한 파일에 액세스하려면 :

import matplotlib.pyplot as plt    
import glob 

for animal_filename in glob.glob('animal_*.csv'): 
    with open(animal_filename, 'rb') as f_input: 
     csv_input = csv.reader(f_input) 
     heading = next(csv_input) 
     x, y = [], [] 

     for row in csv_input: 
      x.append(int(row[1])) 
      y.append(int(row[2])) 

     fig, ax = plt.subplots() 
     plt.title(animal_filename) 
     ax.scatter(x, y) 

plt.show() 
+0

어떻게 내가 XY 좌표를 세우고처럼, 그들에 프로세스를 실행하기를 원한다면 새로 생성 된 파일을 참조하는 것? – Kevin

+0

한 동물 당 하나의 그래프 또는 하나의 그래프에 모든 그래프가 표시됩니까? –

+0

결국 나는 래스터 형식으로 변환 할 arcpy가있는 최소한의 경계 지오메트리를 생성하고 싶습니다. – Kevin

관련 문제