파이썬 for in range 구문 좀 더 직관적이게 바꿀 수 있을까요?

novice의 이미지

OIL.csv
Date,Open,High,Low,Last,Change,Settle,Volume,Open Interest
2016-12-07,51.98,52.28,50.89,50.95,1.03,50.94,315168.0,249919.0
2016-12-06,52.0,52.68,51.38,51.98,0.86,51.97,194699.0,235675.0
2016-12-05,52.57,53.38,51.99,51.99,0.18,52.83,189198.0,220441.0
2016-12-02,52.25,52.69,51.12,52.64,0.69,52.65,179124.0,215723.0
2016-12-01,50.0,52.67,49.94,51.82,1.62,51.96,312215.0,193537.0
...

위의 csv파일을 읽은 후 특정 날짜에서 이전 며칠 전(input_length)까지의 Last 값을 모두 더하는 함수입니다.
ex) 2016-12-07, 2 입력시 처음과 두 번째 행(2016-12-07, 2016-12-06)의 Last 열에서 가져 온 50.95 + 51.98 값을 출력

import pandas as pd
 
input_date = input()
input_length = input()
 
OIL = pd.read_csv("OIL.csv", index_col=['Date'], usecols=[0,1,2,3,4])
 
start = OIL.index.get_loc(input_date) 
end = start + input_length -1 
 
def period_last_sum(input_date, input_length):
 
    global start, end
 
    func_result = 0
 
    for _ in range(start, end+1): 
        func_result = func_result + OIL.iat[start,3]
        start +=1
        print(func_result)
 
    return func_result
 
result = period_last_sum(input_date, input_length)
print(result)

인덱스 행이 0부터 시작하기 때문에 부득이하게 input_length 값에서 1을 빼야 했고,
for in range 구문에서는 원래 end 값이 있어야 하기 때문에 1을 더해야 했습니다.
실행하는 데는 문제가 없지만, 왜지 가독성도 떨어지고 다음에 봤을 때는 내가 왜 이랬는지 주석을 달아도 이해하기 어려울 것 같습니다 -_-;;
어떻게 해야 코드를 직관적으로 바꿀 수 있을까요?

문법에 대해서도 질문 한 가지 드리고 싶습니다.
만약 다른 함수도 추가한다면, 위의 함수에서 global로 전역 변수 start, end를 호출하는 게 잘못된 선택인 것 같습니다. 그런데 저렇게 호출하지 않으면 for _ in range(start, end+1) 구문에서 start와 end를 사용할 수가 없게 되는데, 혹시 두 전역변수의 내용을 바꾸지 않으면서 다른 추가 함수에서도 사용할 수 있는 방법이 있을까요?

jehnpark의 이미지

repeat함수 있을텐데요

Anti-Lock의 이미지

import pandas as pd
 
def period_last_sum(df, input_date, input_length):
 
    start = df.index.get_loc(input_date) 
 
    func_result = 0
    for i in range(start, start + input_length): 
        func_result = func_result + df['Last'][i]
        #print(func_result)
 
    return func_result
 
 
#input_date = input()
#input_length = input()
input_date = '2016-12-07' #XXX: FOR TEST
input_length = '2' #XXX: FOR TEST
 
OIL = pd.read_csv("OIL.csv", index_col=['Date'], usecols=[0,1,2,3,4])
 
result = period_last_sum(OIL, input_date, int(input_length))
print(result)

혹은 다음 함수도 가능합니다.

def period_last_sum2(df, input_date, input_length):
 
    start = df.index.get_loc(input_date) 
 
    func_result = 0
    for val in df['Last'][start : start + input_length]: 
        func_result = func_result + val
        #print(func_result)
 
    return func_result

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.