2017-04-15 19 views
1

私はapplyとlambda関数でコメントアウトされたforループを置き換えようとしていますが、私は以下のエラーを受け取ります。私のpythonは錆びているので、ヒントは非常に高く評価されています。forループをapplyに置き換えよう

エラー:

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

にSyntaxError:無効な構文

コード:

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, 

アイテム、高速パス) 3289(項目)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コードを書くことにもっと精通しています。だから私はループを書くのが好きなので、私は適用でこれをやろうとしているのです。私はまだPythonでこの問題を抱えていますので、大変ありがとうございます。エラーはあなたに意味をなさないのですか?コードを修正する方法を提案できますか? – user3476463

関連する問題