How can I get grouped windows in pandas? I.e. like WINDOW OVER … PARTITION BY … from SQL












0














Pandas window functions i.e. rolling work great. However coming from SQL I know, that windows can also be PARTITIONED BY some group.



How can I get grouped windows in pandas?
A:



df.groupby(['group']).rolling('10s').mean()


fails with:



TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'


And if df.rolling('10s', on='group') is used, it only works in case 'group' is int i.e. in SQL some concrete number of preceding/following rows. How can I preserve the window by time?



edit minimal sample:



import random
groups = ['A', 'B']
df = pd.DataFrame({'value': range(60), 'group': [random.choice(groups) for i in range(60)]},index=pd.DatetimeIndex(pd.date_range(start='20160101', end='20160229')))
df.head()


The following works, but does not consider the groups:



df[['value']].rolling('2d').mean().head()


The following does not work for time windows:



df[['group','value']].rolling(3, on='group').mean().head()


and



df.rolling('2D', on='group').mean().head()


fails with: window must be an integer when trying to use a time window.










share|improve this question





























    0














    Pandas window functions i.e. rolling work great. However coming from SQL I know, that windows can also be PARTITIONED BY some group.



    How can I get grouped windows in pandas?
    A:



    df.groupby(['group']).rolling('10s').mean()


    fails with:



    TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'


    And if df.rolling('10s', on='group') is used, it only works in case 'group' is int i.e. in SQL some concrete number of preceding/following rows. How can I preserve the window by time?



    edit minimal sample:



    import random
    groups = ['A', 'B']
    df = pd.DataFrame({'value': range(60), 'group': [random.choice(groups) for i in range(60)]},index=pd.DatetimeIndex(pd.date_range(start='20160101', end='20160229')))
    df.head()


    The following works, but does not consider the groups:



    df[['value']].rolling('2d').mean().head()


    The following does not work for time windows:



    df[['group','value']].rolling(3, on='group').mean().head()


    and



    df.rolling('2D', on='group').mean().head()


    fails with: window must be an integer when trying to use a time window.










    share|improve this question



























      0












      0








      0







      Pandas window functions i.e. rolling work great. However coming from SQL I know, that windows can also be PARTITIONED BY some group.



      How can I get grouped windows in pandas?
      A:



      df.groupby(['group']).rolling('10s').mean()


      fails with:



      TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'


      And if df.rolling('10s', on='group') is used, it only works in case 'group' is int i.e. in SQL some concrete number of preceding/following rows. How can I preserve the window by time?



      edit minimal sample:



      import random
      groups = ['A', 'B']
      df = pd.DataFrame({'value': range(60), 'group': [random.choice(groups) for i in range(60)]},index=pd.DatetimeIndex(pd.date_range(start='20160101', end='20160229')))
      df.head()


      The following works, but does not consider the groups:



      df[['value']].rolling('2d').mean().head()


      The following does not work for time windows:



      df[['group','value']].rolling(3, on='group').mean().head()


      and



      df.rolling('2D', on='group').mean().head()


      fails with: window must be an integer when trying to use a time window.










      share|improve this question















      Pandas window functions i.e. rolling work great. However coming from SQL I know, that windows can also be PARTITIONED BY some group.



      How can I get grouped windows in pandas?
      A:



      df.groupby(['group']).rolling('10s').mean()


      fails with:



      TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'


      And if df.rolling('10s', on='group') is used, it only works in case 'group' is int i.e. in SQL some concrete number of preceding/following rows. How can I preserve the window by time?



      edit minimal sample:



      import random
      groups = ['A', 'B']
      df = pd.DataFrame({'value': range(60), 'group': [random.choice(groups) for i in range(60)]},index=pd.DatetimeIndex(pd.date_range(start='20160101', end='20160229')))
      df.head()


      The following works, but does not consider the groups:



      df[['value']].rolling('2d').mean().head()


      The following does not work for time windows:



      df[['group','value']].rolling(3, on='group').mean().head()


      and



      df.rolling('2D', on='group').mean().head()


      fails with: window must be an integer when trying to use a time window.







      python pandas pandas-groupby window-functions partition-by






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 at 6:23

























      asked Nov 12 at 5:47









      Georg Heiler

      4,950551125




      4,950551125
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Drop the index so you can group by. I think the issue with the index column.



          df.groupby(['col2','col3'], as_index=False)






          share|improve this answer





















          • but if I drop the index, then I no longer can aggregate by time. I.e. your solution throws: window must be an integer as the independent no longer contains time information.
            – Georg Heiler
            Nov 12 at 5:58












          • then use s.groupby(level=['first','second']) in level specify the index columns
            – AmilaMGunawardana
            Nov 12 at 6:02










          • This does not work, as initially it is not a multi index, but only a time based index. i.e. The second column/level group is not in the index.
            – Georg Heiler
            Nov 12 at 6:10











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256503%2fhow-can-i-get-grouped-windows-in-pandas-i-e-like-window-over-partition-by%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Drop the index so you can group by. I think the issue with the index column.



          df.groupby(['col2','col3'], as_index=False)






          share|improve this answer





















          • but if I drop the index, then I no longer can aggregate by time. I.e. your solution throws: window must be an integer as the independent no longer contains time information.
            – Georg Heiler
            Nov 12 at 5:58












          • then use s.groupby(level=['first','second']) in level specify the index columns
            – AmilaMGunawardana
            Nov 12 at 6:02










          • This does not work, as initially it is not a multi index, but only a time based index. i.e. The second column/level group is not in the index.
            – Georg Heiler
            Nov 12 at 6:10
















          0














          Drop the index so you can group by. I think the issue with the index column.



          df.groupby(['col2','col3'], as_index=False)






          share|improve this answer





















          • but if I drop the index, then I no longer can aggregate by time. I.e. your solution throws: window must be an integer as the independent no longer contains time information.
            – Georg Heiler
            Nov 12 at 5:58












          • then use s.groupby(level=['first','second']) in level specify the index columns
            – AmilaMGunawardana
            Nov 12 at 6:02










          • This does not work, as initially it is not a multi index, but only a time based index. i.e. The second column/level group is not in the index.
            – Georg Heiler
            Nov 12 at 6:10














          0












          0








          0






          Drop the index so you can group by. I think the issue with the index column.



          df.groupby(['col2','col3'], as_index=False)






          share|improve this answer












          Drop the index so you can group by. I think the issue with the index column.



          df.groupby(['col2','col3'], as_index=False)







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 12 at 5:53









          AmilaMGunawardana

          645




          645












          • but if I drop the index, then I no longer can aggregate by time. I.e. your solution throws: window must be an integer as the independent no longer contains time information.
            – Georg Heiler
            Nov 12 at 5:58












          • then use s.groupby(level=['first','second']) in level specify the index columns
            – AmilaMGunawardana
            Nov 12 at 6:02










          • This does not work, as initially it is not a multi index, but only a time based index. i.e. The second column/level group is not in the index.
            – Georg Heiler
            Nov 12 at 6:10


















          • but if I drop the index, then I no longer can aggregate by time. I.e. your solution throws: window must be an integer as the independent no longer contains time information.
            – Georg Heiler
            Nov 12 at 5:58












          • then use s.groupby(level=['first','second']) in level specify the index columns
            – AmilaMGunawardana
            Nov 12 at 6:02










          • This does not work, as initially it is not a multi index, but only a time based index. i.e. The second column/level group is not in the index.
            – Georg Heiler
            Nov 12 at 6:10
















          but if I drop the index, then I no longer can aggregate by time. I.e. your solution throws: window must be an integer as the independent no longer contains time information.
          – Georg Heiler
          Nov 12 at 5:58






          but if I drop the index, then I no longer can aggregate by time. I.e. your solution throws: window must be an integer as the independent no longer contains time information.
          – Georg Heiler
          Nov 12 at 5:58














          then use s.groupby(level=['first','second']) in level specify the index columns
          – AmilaMGunawardana
          Nov 12 at 6:02




          then use s.groupby(level=['first','second']) in level specify the index columns
          – AmilaMGunawardana
          Nov 12 at 6:02












          This does not work, as initially it is not a multi index, but only a time based index. i.e. The second column/level group is not in the index.
          – Georg Heiler
          Nov 12 at 6:10




          This does not work, as initially it is not a multi index, but only a time based index. i.e. The second column/level group is not in the index.
          – Georg Heiler
          Nov 12 at 6:10


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256503%2fhow-can-i-get-grouped-windows-in-pandas-i-e-like-window-over-partition-by%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Error while running script in elastic search , gateway timeout

          Adding quotations to stringified JSON object values