2017-04-15 1 views
1

아래의 for 루프를 apply 및 lambda 함수로 바꾸려고하는데 아래 오류가 나타납니다. 내 파이썬 녹슨, 그래서 어떤 조언을 크게 감사합니다.for 루프를 적용으로 대체하십시오.

오류 :

File "<ipython-input-5-b29bfb93595e>", line 11 
if (dataDF < dataDF.shift()) & (dataDF.shift(periods=1) < dataDF.shift(periods=2)): 
                       ^

구문 에러 : 유효하지 않은 구문

코드 :

def get_recession_end(): 
    dataDF = pd.ExcelFile('gdplev.xls').parse(skiprows=7)[['Unnamed: 4',  'Unnamed: 5']].loc[246:] 
    dataDF.columns = ['Quarter','dataDF'] 
    dataDF['dataDF'] = pd.to_numeric(dataDF['dataDF']) 

    #quarters = [] 
    #for i in range(len(dataDF) - 2): 
     #if (dataDF.iloc[i][1] < dataDF.iloc[i+1][1]) & (dataDF.iloc[i+1][1] <  dataDF.iloc[i+2][1]): 
      #quarters.append(dataDF.iloc[i+2][0]) 
    #return quarters[0] 

    quarters = dataDF.apply(lambda x: quarters = [] 
             if (dataDF < dataDF.shift()) &  (dataDF.shift(periods=1) < dataDF.shift(periods=2)): 
              quarters.append(dataDF.shift(2)[0])) 
    return quarters[0] 

get_recession_end() 

업데이트 새 버전 :

코드 :

def get_recession_end(): 
def get_recession_end(): 
    dataDF = pd.ExcelFile('gdplev.xls').parse(skiprows=7)[['Unnamed: 4', 
'Unnamed: 5']].loc[246:]#skiprows=17,skip_footer=(38)) 
    dataDF.columns = ['Quarter','dataDF'] 
    dataDF['dataDF'] = pd.to_numeric(dataDF['dataDF']) 
    #quarters = [] 
    #for i in range(len(dataDF) - 2): 
     #if (dataDF.iloc[i][1] < dataDF.iloc[i+1][1]) & (dataDF.iloc[i+1][1] 
< dataDF.iloc[i+2][1]): 
      #quarters.append(dataDF.iloc[i+2][0]) 
    #return quarters[0] 
    def do_the_foo(x): 
     quarters = [] 
     if (dataDF < dataDF.shift()) & (dataDF.shift(periods=1) < 
dataDF.shift(periods=2)): 
      quarters.append(dataDF.shift(2)[0]) 
     return quarters 

    quarters = dataDF.loc[:(len(dataDF) - 2)].apply(do_the_foo) 
    return quarters[0] 


get_recession_end() 

새로운 오류 :

--------------------------------------------------------------------------- 
KeyError         Traceback (most recent call last) 
/opt/conda/lib/python3.5/site-packages/pandas/indexes/base.py in 
get_loc(self, key, method, tolerance) 
    1944    try: 
-> 1945     return self._engine.get_loc(key) 
    1946    except KeyError: 

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)() 

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)() 

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item 
(pandas/hashtable.c:12368)() 

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item 
(pandas/hashtable.c:12322)() 

KeyError: 0 

During handling of the above exception, another exception occurred: 

KeyError         Traceback (most recent call last) 
<ipython-input-10-53e0a21f9faa> in <module>() 
    18 
19 
---> 20 get_recession_end() 

<ipython-input-10-53e0a21f9faa> in get_recession_end() 
    15 
    16  quarters = dataDF.loc[:-(len(dataDF) - 2)].apply(do_the_foo) 
---> 17  return quarters[0] 
    18 
    19 

/opt/conda/lib/python3.5/site-packages/pandas/core/frame.py in 
__getitem__(self, key) 
    1995    return self._getitem_multilevel(key) 
    1996   else: 
-> 1997    return self._getitem_column(key) 
    1998 
    1999  def _getitem_column(self, key): 

/opt/conda/lib/python3.5/site-packages/pandas/core/frame.py in 
_getitem_column(self, key) 
    2002   # get column 
    2003   if self.columns.is_unique: 
-> 2004    return self._get_item_cache(key) 
    2005 
    2006   # duplicate columns & possible reduce dimensionality 

/opt/conda/lib/python3.5/site-packages/pandas/core/generic.py in 
_get_item_cache(self, item) 
    1348   res = cache.get(item) 
    1349   if res is None: 
-> 1350    values = self._data.get(item) 
    1351    res = self._box_item_values(item, values) 
    1352    cache[item] = res 

/opt/conda/lib/python3.5/site-packages/pandas/core/internals.py in get(self, 

항목, 빠른 경로) 3,289하지 ISNULL (항목 경우) : -> 3290 LOC = self.items.get_loc (항목) 다른 3291 : 3292 인덱서 = np.arange (LEN (self.items)) [ISNULL (self.items가)]

/opt/conda/lib/python3.5/site-packages/pandas/indexes/base.py in 
get_loc(self, key, method, tolerance) 
    1945     return self._engine.get_loc(key) 
    1946    except KeyError: 
-> 1947     return 
self._engine.get_loc(self._maybe_cast_indexer(key)) 
    1948 
    1949   indexer = self.get_indexer([key], method=method, 
tolerance=tolerance) 

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)() 

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)() 

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item 
(pandas/hashtable.c:12368)() 

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item 
(pandas/hashtable.c:12322)() 

KeyError: 0 

답변

0

lambda expressions 한 식에 한정된다. 여러 문장을 사용하려고했습니다. 람다 식은 작은 함수를 인라인하는 편리한 방법 일 뿐이며 항상 정규 함수로 대체 될 수 있습니다. 람다가 외부 함수 범위의 변수를 참조하기 때문에 대체 함수도 해당 범위에 정의되어야합니다.

결과가 대체하려는 원본보다 좋지 않습니다. 그래서, 나는 진짜 대답은 당신이 이런 식으로 람다를 사용할 수 없다고 생각합니다.

def get_recession_end(): 
    dataDF = pd.ExcelFile('gdplev.xls').parse(skiprows=7)[['Unnamed: 4',  'Unnamed: 5']].loc[246:] 
    dataDF.columns = ['Quarter','dataDF'] 
    dataDF['dataDF'] = pd.to_numeric(dataDF['dataDF']) 

    #quarters = [] 
    #for i in range(len(dataDF) - 2): 
     #if (dataDF.iloc[i][1] < dataDF.iloc[i+1][1]) & (dataDF.iloc[i+1][1] <  dataDF.iloc[i+2][1]): 
      #quarters.append(dataDF.iloc[i+2][0]) 
    #return quarters[0] 

    def do_the_foo(x): 
     quarters = [] 
     if (dataDF < dataDF.shift()) & (dataDF.shift(periods=1) < dataDF.shift(periods=2)): 
      quarters.append(dataDF.shift(2)[0]) 
     return quarters 

    quarters = dataDF.apply(do_the_foo) 

get_recession_end() 
+0

다시 연락해 주셔서 감사합니다. 나는 당신의 제안을 덧붙이려고했다. 위의 새 코드가 "업데이트 된 새 버전"에 있는데 새로운 오류가 나타납니다. 나는 r 코드 작성에 익숙하다. 따라서 필자는 루프를 작성하는 데 적용하는 것을 선호합니다. 그 이유는 적용을 통해이를 수행하려고하는 이유입니다. 나는 아직도 파이썬으로이 문제에 매달려있다. 도움을 주셔서 대단히 감사한다. 오류가 이해 되는가? 코드 수정 방법을 제안 할 수 있습니까? – user3476463