Python pandas: calculate rolling mean based on multiple criteriaSelecting multiple columns in a pandas dataframeAdding new column to existing DataFrame in Python pandasSelect rows from a DataFrame based on values in a column in pandasRolling Mean of Rolling Correlation dataframe in Python?Rolling mean is not shown on my graphPython Pandas: calculate rolling mean (moving average) over variable number of rowsPython Pandas rolling mean with window value in another columnpython pandas calculate a meanrolling weighted moving average pandasCalculate the Mean of last 3 records in a timeseries data in pandas

Russian word for a male zebra

Why does ''cat "$1:-/dev/stdin | ... &>/dev/null'' work in bash but not dash?

With Ubuntu 18.04, how can I have a hot corner that locks the computer?

Non-aqueous eyes?

Code downloads a text file from a website, saves it to local disk, and then loads it into a list for further processing

60s or 70s novel about Empire of Man making 1st contact with 1st discovered alien race

How to trick the reader into thinking they're following a redshirt instead of the protagonist?

Proving that a Russian cryptographic standard is too structured

What's the difference between the Add and Linear Dodge blend modes in After Effects?

If I leave the US through an airport, do I have to return through the same airport?

Does the new finding on "reversing a quantum jump mid-flight" rule out any interpretations of QM?

Which languages would be most useful in Europe at the end of the 19th century?

Why can my keyboard only digest 6 keypresses at a time?

Why am I getting a strange double quote (“) in Open Office instead of the ordinary one (")?

Are polynomials with the same roots identical?

How to you show a 3-center 2-electron bond in a Lewis structure?

Excel division by 0 error when trying to average results of formulas

Is there a set of positive integers of density 1 which contains no infinite arithmetic progression?

I have a problematic assistant manager, but I can't fire him

What are neighboring ports?

The Frozen Wastes

Why can I traceroute to this IP address, but not ping?

How can I make 12 tone and atonal melodies sound interesting?

What would be the way to say "just saying" in German? (Not the literal translation)



Python pandas: calculate rolling mean based on multiple criteria


Selecting multiple columns in a pandas dataframeAdding new column to existing DataFrame in Python pandasSelect rows from a DataFrame based on values in a column in pandasRolling Mean of Rolling Correlation dataframe in Python?Rolling mean is not shown on my graphPython Pandas: calculate rolling mean (moving average) over variable number of rowsPython Pandas rolling mean with window value in another columnpython pandas calculate a meanrolling weighted moving average pandasCalculate the Mean of last 3 records in a timeseries data in pandas






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have a dataframe that shows the closing value for a bunch of stocks for the last 10 days. It has a datetime index & stocks can be identified by their name/code. Can you help me figure out how to calculate the 4 day moving average for each separate stock in the dataframe?



I've tried to use the pd.DataFrame.rolling().mean() method but it just gives the rolling mean for the whole dataset. Not sure where to go next...



sampleData = hundredDayData['2019-03-11':'2019-03-20']
sampleData['Close: 4 day mean'] = sampleData['Close'].rolling(window=4).mean()
sampleData.head(24)

enter image description here










share|improve this question




























    0















    I have a dataframe that shows the closing value for a bunch of stocks for the last 10 days. It has a datetime index & stocks can be identified by their name/code. Can you help me figure out how to calculate the 4 day moving average for each separate stock in the dataframe?



    I've tried to use the pd.DataFrame.rolling().mean() method but it just gives the rolling mean for the whole dataset. Not sure where to go next...



    sampleData = hundredDayData['2019-03-11':'2019-03-20']
    sampleData['Close: 4 day mean'] = sampleData['Close'].rolling(window=4).mean()
    sampleData.head(24)

    enter image description here










    share|improve this question
























      0












      0








      0








      I have a dataframe that shows the closing value for a bunch of stocks for the last 10 days. It has a datetime index & stocks can be identified by their name/code. Can you help me figure out how to calculate the 4 day moving average for each separate stock in the dataframe?



      I've tried to use the pd.DataFrame.rolling().mean() method but it just gives the rolling mean for the whole dataset. Not sure where to go next...



      sampleData = hundredDayData['2019-03-11':'2019-03-20']
      sampleData['Close: 4 day mean'] = sampleData['Close'].rolling(window=4).mean()
      sampleData.head(24)

      enter image description here










      share|improve this question














      I have a dataframe that shows the closing value for a bunch of stocks for the last 10 days. It has a datetime index & stocks can be identified by their name/code. Can you help me figure out how to calculate the 4 day moving average for each separate stock in the dataframe?



      I've tried to use the pd.DataFrame.rolling().mean() method but it just gives the rolling mean for the whole dataset. Not sure where to go next...



      sampleData = hundredDayData['2019-03-11':'2019-03-20']
      sampleData['Close: 4 day mean'] = sampleData['Close'].rolling(window=4).mean()
      sampleData.head(24)

      enter image description here







      python python-3.x pandas






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 19:45









      AbhayAbhay

      519




      519






















          1 Answer
          1






          active

          oldest

          votes


















          1














          df = pd.DataFrame('code': ['a']*10+['b']*10, 'Close': [1]*20)
          df.groupby('code')['Close'].rolling(window=4).mean().reset_index()


          • Group by code and calculate rolling mean with in the group

          Note: If your code's are all jumbled (as shown below), then you should be using



          df = pd.DataFrame('code': ['a']*10+['b']*10+['a']*10, 'Close': [1]*30)
          rolling = df.groupby('code')['Close'].rolling(window=4).mean().reset_index().set_index('level_1').rename(
          columns='Close':'rolling')[['rolling']]
          df.merge(rolling, left_index=True, right_index=True)


          Calculate rolling mean at group level but use the index to merge it back into the main dataframe as a new column.






          share|improve this answer

























          • This works, thanks for your help!

            – Abhay
            Mar 25 at 7:08











          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%2f55327858%2fpython-pandas-calculate-rolling-mean-based-on-multiple-criteria%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









          1














          df = pd.DataFrame('code': ['a']*10+['b']*10, 'Close': [1]*20)
          df.groupby('code')['Close'].rolling(window=4).mean().reset_index()


          • Group by code and calculate rolling mean with in the group

          Note: If your code's are all jumbled (as shown below), then you should be using



          df = pd.DataFrame('code': ['a']*10+['b']*10+['a']*10, 'Close': [1]*30)
          rolling = df.groupby('code')['Close'].rolling(window=4).mean().reset_index().set_index('level_1').rename(
          columns='Close':'rolling')[['rolling']]
          df.merge(rolling, left_index=True, right_index=True)


          Calculate rolling mean at group level but use the index to merge it back into the main dataframe as a new column.






          share|improve this answer

























          • This works, thanks for your help!

            – Abhay
            Mar 25 at 7:08















          1














          df = pd.DataFrame('code': ['a']*10+['b']*10, 'Close': [1]*20)
          df.groupby('code')['Close'].rolling(window=4).mean().reset_index()


          • Group by code and calculate rolling mean with in the group

          Note: If your code's are all jumbled (as shown below), then you should be using



          df = pd.DataFrame('code': ['a']*10+['b']*10+['a']*10, 'Close': [1]*30)
          rolling = df.groupby('code')['Close'].rolling(window=4).mean().reset_index().set_index('level_1').rename(
          columns='Close':'rolling')[['rolling']]
          df.merge(rolling, left_index=True, right_index=True)


          Calculate rolling mean at group level but use the index to merge it back into the main dataframe as a new column.






          share|improve this answer

























          • This works, thanks for your help!

            – Abhay
            Mar 25 at 7:08













          1












          1








          1







          df = pd.DataFrame('code': ['a']*10+['b']*10, 'Close': [1]*20)
          df.groupby('code')['Close'].rolling(window=4).mean().reset_index()


          • Group by code and calculate rolling mean with in the group

          Note: If your code's are all jumbled (as shown below), then you should be using



          df = pd.DataFrame('code': ['a']*10+['b']*10+['a']*10, 'Close': [1]*30)
          rolling = df.groupby('code')['Close'].rolling(window=4).mean().reset_index().set_index('level_1').rename(
          columns='Close':'rolling')[['rolling']]
          df.merge(rolling, left_index=True, right_index=True)


          Calculate rolling mean at group level but use the index to merge it back into the main dataframe as a new column.






          share|improve this answer















          df = pd.DataFrame('code': ['a']*10+['b']*10, 'Close': [1]*20)
          df.groupby('code')['Close'].rolling(window=4).mean().reset_index()


          • Group by code and calculate rolling mean with in the group

          Note: If your code's are all jumbled (as shown below), then you should be using



          df = pd.DataFrame('code': ['a']*10+['b']*10+['a']*10, 'Close': [1]*30)
          rolling = df.groupby('code')['Close'].rolling(window=4).mean().reset_index().set_index('level_1').rename(
          columns='Close':'rolling')[['rolling']]
          df.merge(rolling, left_index=True, right_index=True)


          Calculate rolling mean at group level but use the index to merge it back into the main dataframe as a new column.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 24 at 20:22

























          answered Mar 24 at 19:54









          mujjigamujjiga

          4,06011321




          4,06011321












          • This works, thanks for your help!

            – Abhay
            Mar 25 at 7:08

















          • This works, thanks for your help!

            – Abhay
            Mar 25 at 7:08
















          This works, thanks for your help!

          – Abhay
          Mar 25 at 7:08





          This works, thanks for your help!

          – Abhay
          Mar 25 at 7:08

















          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.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55327858%2fpython-pandas-calculate-rolling-mean-based-on-multiple-criteria%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript