How would I group by unique values that are in a list form?
If I wanted to get the mean of the past 2 values based on column id
, I would do the following:
df['rolling_mean_2'] = df.groupby('id').apply(lambda x: x.rolling(2, min_periods=2).mean())
>> id value rolling_mean_2
0 b 1 NaN
1 b 3 2
2 d 5 NaN
3 d 7 6
Right, straightforward.
Ok, now let's say my id are in a list form with 4 unique values (a, b, c, d)
x = [{'id': ['a','b','d'], 'value':1},
{'id': ['b','a','d'], 'value':3},
{'id': ['b','a','d'], 'value':5},
{'id': ['a','b','c'], 'value':7}]
df = pd.DataFrame(x)
Now, how would I get the mean from the past 2 values (incl. current row) based on unique value that contains in the list? Thus, my expected output would be as follows:
I'm only going to use variable a and d to keep tidiness and simplicity.
>> id value a_rolling_mean_2 d_rolling_mean_2
0 [a, b, d] 1 NaN NaN
1 [b, a, d] 3 2 2
2 [b, a, d] 5 4 4
3 [a, b, c] 7 6 NaN
python python-3.x pandas lambda pandas-groupby
add a comment |
If I wanted to get the mean of the past 2 values based on column id
, I would do the following:
df['rolling_mean_2'] = df.groupby('id').apply(lambda x: x.rolling(2, min_periods=2).mean())
>> id value rolling_mean_2
0 b 1 NaN
1 b 3 2
2 d 5 NaN
3 d 7 6
Right, straightforward.
Ok, now let's say my id are in a list form with 4 unique values (a, b, c, d)
x = [{'id': ['a','b','d'], 'value':1},
{'id': ['b','a','d'], 'value':3},
{'id': ['b','a','d'], 'value':5},
{'id': ['a','b','c'], 'value':7}]
df = pd.DataFrame(x)
Now, how would I get the mean from the past 2 values (incl. current row) based on unique value that contains in the list? Thus, my expected output would be as follows:
I'm only going to use variable a and d to keep tidiness and simplicity.
>> id value a_rolling_mean_2 d_rolling_mean_2
0 [a, b, d] 1 NaN NaN
1 [b, a, d] 3 2 2
2 [b, a, d] 5 4 4
3 [a, b, c] 7 6 NaN
python python-3.x pandas lambda pandas-groupby
add a comment |
If I wanted to get the mean of the past 2 values based on column id
, I would do the following:
df['rolling_mean_2'] = df.groupby('id').apply(lambda x: x.rolling(2, min_periods=2).mean())
>> id value rolling_mean_2
0 b 1 NaN
1 b 3 2
2 d 5 NaN
3 d 7 6
Right, straightforward.
Ok, now let's say my id are in a list form with 4 unique values (a, b, c, d)
x = [{'id': ['a','b','d'], 'value':1},
{'id': ['b','a','d'], 'value':3},
{'id': ['b','a','d'], 'value':5},
{'id': ['a','b','c'], 'value':7}]
df = pd.DataFrame(x)
Now, how would I get the mean from the past 2 values (incl. current row) based on unique value that contains in the list? Thus, my expected output would be as follows:
I'm only going to use variable a and d to keep tidiness and simplicity.
>> id value a_rolling_mean_2 d_rolling_mean_2
0 [a, b, d] 1 NaN NaN
1 [b, a, d] 3 2 2
2 [b, a, d] 5 4 4
3 [a, b, c] 7 6 NaN
python python-3.x pandas lambda pandas-groupby
If I wanted to get the mean of the past 2 values based on column id
, I would do the following:
df['rolling_mean_2'] = df.groupby('id').apply(lambda x: x.rolling(2, min_periods=2).mean())
>> id value rolling_mean_2
0 b 1 NaN
1 b 3 2
2 d 5 NaN
3 d 7 6
Right, straightforward.
Ok, now let's say my id are in a list form with 4 unique values (a, b, c, d)
x = [{'id': ['a','b','d'], 'value':1},
{'id': ['b','a','d'], 'value':3},
{'id': ['b','a','d'], 'value':5},
{'id': ['a','b','c'], 'value':7}]
df = pd.DataFrame(x)
Now, how would I get the mean from the past 2 values (incl. current row) based on unique value that contains in the list? Thus, my expected output would be as follows:
I'm only going to use variable a and d to keep tidiness and simplicity.
>> id value a_rolling_mean_2 d_rolling_mean_2
0 [a, b, d] 1 NaN NaN
1 [b, a, d] 3 2 2
2 [b, a, d] 5 4 4
3 [a, b, c] 7 6 NaN
python python-3.x pandas lambda pandas-groupby
python python-3.x pandas lambda pandas-groupby
asked Nov 27 '18 at 2:00
ChipmunkafyChipmunkafy
13511
13511
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Using concat
with dataframe constructor recreate the dataframe
df=df.rename(columns={'value':'V'})
newdf=pd.concat([df.V,pd.DataFrame(df.id.tolist(),index=df.index)],axis=1)
Then , Using melt
with groupby
rolling
mean
and stack
to get the out put
newdf.reset_index().melt(['index','V']).set_index('index').sort_index().groupby('value').V.rolling(2, min_periods=2).mean().unstack(0)
Out[260]:
value a b c d
index
0 NaN NaN NaN NaN
1 2.0 2.0 NaN 2.0
2 4.0 4.0 NaN 4.0
3 6.0 6.0 NaN NaN
Perfect! Thank you so much
– Chipmunkafy
Nov 27 '18 at 2:49
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%2f53491708%2fhow-would-i-group-by-unique-values-that-are-in-a-list-form%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
Using concat
with dataframe constructor recreate the dataframe
df=df.rename(columns={'value':'V'})
newdf=pd.concat([df.V,pd.DataFrame(df.id.tolist(),index=df.index)],axis=1)
Then , Using melt
with groupby
rolling
mean
and stack
to get the out put
newdf.reset_index().melt(['index','V']).set_index('index').sort_index().groupby('value').V.rolling(2, min_periods=2).mean().unstack(0)
Out[260]:
value a b c d
index
0 NaN NaN NaN NaN
1 2.0 2.0 NaN 2.0
2 4.0 4.0 NaN 4.0
3 6.0 6.0 NaN NaN
Perfect! Thank you so much
– Chipmunkafy
Nov 27 '18 at 2:49
add a comment |
Using concat
with dataframe constructor recreate the dataframe
df=df.rename(columns={'value':'V'})
newdf=pd.concat([df.V,pd.DataFrame(df.id.tolist(),index=df.index)],axis=1)
Then , Using melt
with groupby
rolling
mean
and stack
to get the out put
newdf.reset_index().melt(['index','V']).set_index('index').sort_index().groupby('value').V.rolling(2, min_periods=2).mean().unstack(0)
Out[260]:
value a b c d
index
0 NaN NaN NaN NaN
1 2.0 2.0 NaN 2.0
2 4.0 4.0 NaN 4.0
3 6.0 6.0 NaN NaN
Perfect! Thank you so much
– Chipmunkafy
Nov 27 '18 at 2:49
add a comment |
Using concat
with dataframe constructor recreate the dataframe
df=df.rename(columns={'value':'V'})
newdf=pd.concat([df.V,pd.DataFrame(df.id.tolist(),index=df.index)],axis=1)
Then , Using melt
with groupby
rolling
mean
and stack
to get the out put
newdf.reset_index().melt(['index','V']).set_index('index').sort_index().groupby('value').V.rolling(2, min_periods=2).mean().unstack(0)
Out[260]:
value a b c d
index
0 NaN NaN NaN NaN
1 2.0 2.0 NaN 2.0
2 4.0 4.0 NaN 4.0
3 6.0 6.0 NaN NaN
Using concat
with dataframe constructor recreate the dataframe
df=df.rename(columns={'value':'V'})
newdf=pd.concat([df.V,pd.DataFrame(df.id.tolist(),index=df.index)],axis=1)
Then , Using melt
with groupby
rolling
mean
and stack
to get the out put
newdf.reset_index().melt(['index','V']).set_index('index').sort_index().groupby('value').V.rolling(2, min_periods=2).mean().unstack(0)
Out[260]:
value a b c d
index
0 NaN NaN NaN NaN
1 2.0 2.0 NaN 2.0
2 4.0 4.0 NaN 4.0
3 6.0 6.0 NaN NaN
answered Nov 27 '18 at 2:15
Wen-BenWen-Ben
112k83267
112k83267
Perfect! Thank you so much
– Chipmunkafy
Nov 27 '18 at 2:49
add a comment |
Perfect! Thank you so much
– Chipmunkafy
Nov 27 '18 at 2:49
Perfect! Thank you so much
– Chipmunkafy
Nov 27 '18 at 2:49
Perfect! Thank you so much
– Chipmunkafy
Nov 27 '18 at 2:49
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%2f53491708%2fhow-would-i-group-by-unique-values-that-are-in-a-list-form%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