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;
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)
python python-3.x pandas
add a comment |
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)
python python-3.x pandas
add a comment |
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)
python python-3.x pandas
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)
python python-3.x pandas
python python-3.x pandas
asked Mar 24 at 19:45
AbhayAbhay
519
519
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
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.
This works, thanks for your help!
– Abhay
Mar 25 at 7:08
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
This works, thanks for your help!
– Abhay
Mar 25 at 7:08
add a comment |
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.
This works, thanks for your help!
– Abhay
Mar 25 at 7:08
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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