2013-10-09 4 views
0

csv 파일의 각 개별 열에서 스크립트를 실행하려고합니다. 파이썬에서 어떤 스크립트를 실행하고 싶은지를 파이썬에게 알려주는 방법을 알아 냈습니다. 그러나 필자는이 칼럼을 분석하고, 결과를 출력하고, 칼럼 2로 옮기고, 파일을 계속해서 실행하기를 원합니다. 내가 원하는 것은 "if etc goto etc"명령입니다. 간단한 oneliner로이 작업을 수행하는 방법을 찾았지만 더 큰 스크립트가 있습니다. 내가 뭔가를 놓친 것 같아서 도움이 될 것입니다. 마치 내가 내 데이터 (h = data)를 정의하는 곳으로 되돌아 갈 수 있지만 다음 열을 선택하라는 말처럼. 여기에 내 대본이있다.CSV의 다음 열로 돌아 가기

import numpy as np 
import matplotlib.pyplot as plt 
from pylab import * 
import pylab 
from scipy import linalg 
import sys 
import scipy.interpolate as interpolate 
import scipy.optimize as optimize 

a=raw_input("Data file name? ") #Name of the data file including the directory, must be .csv 

datafile = open(a, 'r') 
data = [] 
for row in datafile: 
    data.append(row.strip().split(',')) #opening and organizing the csv file 
print('Data points= ', len(data)) 
print data 
c=raw_input("Is there a header row? y/n?") #Remove header line if present 
if c is ('y'): 
    del data[0] 
    data2=data 
    print('Raw data= ', data2) 
else: 
    print('Raw data= ', data) 
''' 
#if I wanted to select a column 
b=input("What column to analyze?") #Asks what column depth data is in 
if b is 1: 
    h=[[rowa[i] for rowa in data] for i in range(1)] #first row 
''' 
h=data # all columns 
g=reduce(lambda x,y: x+y,h) #prepares data for calculations 
a=map(float, g) 
a.sort() 
print ('Organized data= ',a) 

def GRLC(values): 
    ''' 
    Calculate Gini index, Gini coefficient, Robin Hood index, and points of 
    Lorenz curve based on the instructions given in 
    www.peterrosenmai.com/lorenz-curve-graphing-tool-and-gini-coefficient-calculator 
    Lorenz curve values as given as lists of x & y points [[x1, x2], [y1, y2]] 
    @param values: List of values 
    @return: [Gini index, Gini coefficient, Robin Hood index, [Lorenz curve]] 
    ''' 

    n = len(values) 
    assert(n > 0), 'Empty list of values' 
    sortedValues = sorted(values) #Sort smallest to largest 

    #Find cumulative totals 
    cumm = [0] 
    for i in range(n): 
     cumm.append(sum(sortedValues[0:(i + 1)])) 

    #Calculate Lorenz points 
    LorenzPoints = [[], []] 
    sumYs = 0   #Some of all y values 
    robinHoodIdx = -1 #Robin Hood index max(x_i, y_i) 
    for i in range(1, n + 2): 
     x = 100.0 * (i - 1)/n 
     y = 100.0 * (cumm[i - 1]/float(cumm[n])) 
     LorenzPoints[0].append(x) 
     LorenzPoints[1].append(y) 
     sumYs += y 
     maxX_Y = x - y 
     if maxX_Y > robinHoodIdx: robinHoodIdx = maxX_Y 

    giniIdx = 100 + (100 - 2 * sumYs)/n #Gini index 

    return [giniIdx, giniIdx/100, robinHoodIdx, LorenzPoints] 

result = GRLC(a) 
print 'Gini Index', result[0] 
print 'Gini Coefficient', result[1] 
print 'Robin Hood Index', result[2] 
+0

4-5 줄의 샘플 데이터를 게시하면 솔루션을 테스트하는 것이 더 쉬울 수도 있습니다. –

+0

죄송합니다. 예를 들어 지니 (Gini) 계산기 일 뿐이므로 주간 급여 1 = 1234,2342,2234,2121,5677,4553, 급여 2 = 2342,23455,234,7564,43223,12213이라고 할 수 있습니다. csv 파일의 각 열에 급여가있는 경우. – user2843767

답변

0

나는 모든 GRLC 기능을 무시하고 루핑 질문 만 해결합니다. 이것을 시도하십시오. 그것은 while True:을 사용하여 영원히 반복합니다 (프로그램을 끝내면 시작할 수 있으며, Windows에서는 Ctrl + C, OS에 따라 다름). 한 번 csv에서 데이터를로드 한 다음 루프 할 때마다 일부 변수를 다시 빌드 할 수 있습니다. 궁금한 점이 있으면 질문하십시오. 또한 NumPy 패키지를 모두 설치하지 않았으므로 테스트하지 않았습니다.

import numpy as np 
import matplotlib.pyplot as plt 
from pylab import * 
import pylab 
from scipy import linalg 
import sys 
import scipy.interpolate as interpolate 
import scipy.optimize as optimize 

def GRLC(values): 
    ''' 
    Calculate Gini index, Gini coefficient, Robin Hood index, and points of 
    Lorenz curve based on the instructions given in 
    www.peterrosenmai.com/lorenz-curve-graphing-tool-and-gini-coefficient-calculator 
    Lorenz curve values as given as lists of x & y points [[x1, x2], [y1, y2]] 
    @param values: List of values 
    @return: [Gini index, Gini coefficient, Robin Hood index, [Lorenz curve]] 
    ''' 

    n = len(values) 
    assert(n > 0), 'Empty list of values' 
    sortedValues = sorted(values) #Sort smallest to largest 

    #Find cumulative totals 
    cumm = [0] 
    for i in range(n): 
     cumm.append(sum(sortedValues[0:(i + 1)])) 

    #Calculate Lorenz points 
    LorenzPoints = [[], []] 
    sumYs = 0   #Some of all y values 
    robinHoodIdx = -1 #Robin Hood index max(x_i, y_i) 
    for i in range(1, n + 2): 
     x = 100.0 * (i - 1)/n 
     y = 100.0 * (cumm[i - 1]/float(cumm[n])) 
     LorenzPoints[0].append(x) 
     LorenzPoints[1].append(y) 
     sumYs += y 
     maxX_Y = x - y 
     if maxX_Y > robinHoodIdx: robinHoodIdx = maxX_Y 

    giniIdx = 100 + (100 - 2 * sumYs)/n #Gini index 

    return [giniIdx, giniIdx/100, robinHoodIdx, LorenzPoints] 

#Name of the data file including the directory, must be .csv 
a=raw_input("Data file name? ") 

datafile = open(a.strip(), 'r') 
data = [] 

#opening and organizing the csv file 
for row in datafile: 
    data.append(row.strip().split(',')) 

#Remove header line if present 
c=raw_input("Is there a header row? y/n?") 
if c.strip().lower() == ('y'): 
    del data[0] 

while True : 
    #if I want the first column, that's index 0. 
    b=raw_input("What column to analyze?") 

    # Validate that the column input data is correct here. Otherwise it might be out of range, etc. 
    # Maybe try this. You might want more smarts in there, depending on your intent: 
    b = int(b.strip()) 

    # If you expect the user to inpt "2" to mean the second column, you're going to use index 1 (list indexes are 0 based) 
    h=[[rowa[b-1] for rowa in data] for i in range(1)] 

    # prepares data for calculations 
    g=reduce(lambda x,y: x+y,h) 
    a=map(float, g) 
    a.sort() 
    print ('Organized data= ',a) 

    result = GRLC(a) 
    print 'Gini Index', result[0] 
    print 'Gini Coefficient', result[1] 
    print 'Robin Hood Index', result[2] 
+0

또한 주석을 인라인 대신 줄 위에 놓아야합니다 (그래서 각 줄에 길이를 추가하지 않고 맨 위에 쌓습니다). 가독성을 높이기위한 Python 표준이 있습니다. 관심이 있으시고 시간이 있으시다면, 이것은 괜찮습니다 [read] (http://www.python.org/dev/peps/pep-0008/) –

+0

예. 그게 다야. 나는 '진실한 동안'명령에 익숙하지 않다. 그러나 그것은 효과적이다. 결국 나는 사용자 다. 그러나 이것은 내가 지금 일주일 동안하려고 노력했던 것이다. 감사. – user2843767

+0

해결책 인 경우 답변으로 선택할 수 있습니까? 'while '은 파이썬에서 반복자의 한 유형입니다. 조건이 더 이상 충족되지 않을 때까지 반복 될 것이고, 'True'가 항상 만족되기 때문에, 그것은 영원히 반복 할 것입니다. –