가 자신의 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()
어떻게 내가 XY 좌표를 세우고처럼, 그들에 프로세스를 실행하기를 원한다면 새로 생성 된 파일을 참조하는 것? – Kevin
한 동물 당 하나의 그래프 또는 하나의 그래프에 모든 그래프가 표시됩니까? –
결국 나는 래스터 형식으로 변환 할 arcpy가있는 최소한의 경계 지오메트리를 생성하고 싶습니다. – Kevin