2017-01-18 24 views
2

これは私の以前の問題の幾分拡張です python pandas rolling function with two argumentsグループ化されたDataFrameで2つの引数を持つPython pandas rolling関数

グループごとに同じ方法を実行するにはどうすればよいですか。下の 'C'列がグループ化に使用されているとします。

私はに苦しんでいます:kendalltauのような二つの引数を、取ってローリング機能を適用、並べ替え、各グループをWithing「」

  • により、各グループ内で列「C」
  • によって

    1. グループ引数 'A'と 'B'に変換します。上記のリンクが、この複雑で説明したように、私は「インデックスを渡す」回避策をしようとしている

      expected result

      :期待される結果は以下のようなDATAFRAMEだろう

    ケースは、私はランダムに生成されたデータを使用し簡単にするためにのでこれは、ないそこまで私が働いているものと、おもちゃの一例である。:-(私のスキルを超えている。

    rand = np.random.RandomState(1) 
    dff = pd.DataFrame({'A' : np.arange(20), 
            'B' : rand.randint(100, 120, 20), 
            'C' : rand.randint(0, 2, 20)}) 
    
    def my_tau_indx(indx): 
        x = dff.iloc[indx, 0] 
        y = dff.iloc[indx, 1] 
        tau = sp.stats.mstats.kendalltau(x, y)[0] 
        return tau 
    
    dff['tau'] = dff.sort_values(['C', 'A']).groupby('C').rolling(window = 5).apply(my_tau_indx, args = ([dff.index.values])) 
    

    すべては、私はCを作る修正しますまだ別のバグがあります...

    上記の問題はNickil Maveliによって解決され、numpy 1.11.0、pandas 0.18.1、scipy 0.17.1、conda 4.1.4で動作します。それはいくつかの警告を生成しますが、動作します。私の別のマシンで


    と最新&最大のnumpyの1.12.0、0.19.2時点パンダ、0.18.1 scipyのダウンロード、condaバージョン3.10.0およびBLAS/LAPACKは - それは動作しませんし、私は以下のトレースバックを得ます。これはバージョンが関連しているようですが、1台目のマシンをアップグレードしてから動作しなくなってしまったようです...科学の名前で... ;-)

    Nickilが示唆したように、これはnumpy 1.11と1.12の間に互換性がないためでした。 numpyのダウングレードは助けになりました。私はBLAS/LAPACKをWindows上に持っていたので、http://www.lfd.uci.edu/~gohlke/pythonlibs/から1.11.3 + mklをインストールしました。

    Traceback (most recent call last): 
    
    File "<ipython-input-4-bbca2c0e986b>", line 16, in <module> 
    t = grp.apply(func) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\groupby.py", line 651, in apply 
    return self._python_apply_general(f) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\groupby.py", line 655, in _python_apply_general 
    self.axis) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\groupby.py", line 1527, in apply 
    res = f(group) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\groupby.py", line 647, in f 
    return func(g, *args, **kwargs) 
    
    File "<ipython-input-4-bbca2c0e986b>", line 15, in <lambda> 
    func = lambda x: pd.Series(pd.rolling_apply(np.arange(len(x)), 5, my_tau_indx), x.index) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\stats\moments.py", line 584, in rolling_apply 
    kwargs=kwargs) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\stats\moments.py", line 240, in ensure_compat 
    result = getattr(r, name)(*args, **kwds) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\window.py", line 863, in apply 
    return super(Rolling, self).apply(func, args=args, kwargs=kwargs) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\window.py", line 621, in apply 
    center=False) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\window.py", line 560, in _apply 
    result = calc(values) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\window.py", line 555, in calc 
    return func(x, window, min_periods=self.min_periods) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\window.py", line 618, in f 
    kwargs) 
    
    File "pandas\algos.pyx", line 1831, in pandas.algos.roll_generic (pandas\algos.c:51768) 
    
    File "<ipython-input-4-bbca2c0e986b>", line 8, in my_tau_indx 
    x = dff.iloc[indx, 0] 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\indexing.py", line 1294, in __getitem__ 
    return self._getitem_tuple(key) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\indexing.py", line 1560, in _getitem_tuple 
    retval = getattr(retval, self.name)._getitem_axis(key, axis=axis) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\indexing.py", line 1614, in _getitem_axis 
    return self._get_loc(key, axis=axis) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\indexing.py", line 96, in _get_loc 
    return self.obj._ixs(key, axis=axis) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\core\frame.py", line 1908, in _ixs 
    label = self.index[i] 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\indexes\range.py", line 510, in __getitem__ 
    return super_getitem(key) 
    
    File "C:\Apps\Anaconda\v2_1_0_x64\envs\python35\lib\site-packages\pandas\indexes\base.py", line 1275, in __getitem__ 
    result = getitem(key) 
    
    IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices 
    

    最終チェック:達成する

    enter image description here

  • +0

    予想される出力とは何ですか? –

    +0

    @Andrew L - ありがとう、私は間違ってこれが推測できると仮定した。今はっきりしていることを願っています。 – rpl

    答えて

    1

    一つの方法は、すべてのグループを反復処理し、すべてのそのようなグループにpd.rolling_applyを使用することです。

    import scipy.stats as ss 
    
    def my_tau_indx(indx): 
        x = dff.iloc[indx, 0] 
        y = dff.iloc[indx, 1] 
        tau = ss.mstats.kendalltau(x, y)[0] 
        return tau 
    
    grp = dff.sort_values(['A', 'C']).groupby('C', group_keys=False) 
    func = lambda x: pd.Series(pd.rolling_apply(np.arange(len(x)), 5, my_tau_indx), x.index) 
    t = grp.apply(func) 
    dff.reindex(t.index).assign(tau=t) 
    

    enter image description here


    EDITは:

    def my_tau_indx(indx): 
        x = dff.ix[indx, 0] 
        y = dff.ix[indx, 1] 
        tau = ss.mstats.kendalltau(x, y)[0] 
        return tau 
    
    grp = dff.sort_values(['A', 'C']).groupby('C', group_keys=False) 
    t = grp.rolling(5).apply(my_tau_indx).get('A') 
    
    grp.head(dff.shape[0]).reindex(t.index).assign(tau=t) 
    

    enter image description here

    +1

    ソリューションを投稿していただきありがとうございます。 'pd.rolling_apply'は廃止予定ですので、' rolling'と同じように実現する方法があるのだろうか?また、(これは私の好奇心です)グローバル変数を変更する関数に依存しないソリューションはあなたの頭に浮かんでいますか? – rpl

    +1

    'DF.rolling()。apply()'は、現在の形式のカスタム関数からスカラー値を返すことができるとは思いません。代わりに、スライディングウィンドウリストの理解度を使用してこれを再設計し、あまりにも多くの努力のように見える行単位でこのようなさまざまな計算を連結することがあります。今は 'pd.rolling_apply()'に固執して、今後のバージョンで改良版がリリースされるまで待つか、この懸念に対処するgithubで問題を投稿する**(https://github.com)/pandas-dev/pandas/issues) –

    +0

    完全なトレースバックを使用して質問を編集して、簡単にデバッグできますか?以前は正しく動作していましたか? –

    関連する問題