Value assignment between Series using .loc, same size with different indices Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!What is the difference between old style and new style classes in Python?Is there a difference between “==” and “is”?What is the difference between @staticmethod and @classmethod?Difference between append vs. extend list methods in PythonWhat's the difference between lists and tuples?Difference between __str__ and __repr__?What are the differences between type() and isinstance()?What is the difference between dict.items() and dict.iteritems()?How are iloc, ix and loc different?pandas: Assign values to a slice a MultiIndex by range of secondary index
What makes a man succeed?
Misunderstanding of Sylow theory
Crossing US/Canada Border for less than 24 hours
Google .dev domain strangely redirects to https
What does it mean that physics no longer uses mechanical models to describe phenomena?
How could we fake a moon landing now?
What are the discoveries that have been possible with the rejection of positivism?
Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?
How can I set the aperture on my DSLR when it's attached to a telescope instead of a lens?
What is an "asse" in Elizabethan English?
Is CEO the "profession" with the most psychopaths?
What order were files/directories output in dir?
Trademark violation for app?
Flash light on something
What is the chair depicted in Cesare Maccari's 1889 painting "Cicerone denuncia Catilina"?
Why is it faster to reheat something than it is to cook it?
What initially awakened the Balrog?
Why does it sometimes sound good to play a grace note as a lead in to a note in a melody?
Can the Flaming Sphere spell be rammed into multiple Tiny creatures that are in the same 5-foot square?
An adverb for when you're not exaggerating
How many time has Arya actually used Needle?
How were pictures turned from film to a big picture in a picture frame before digital scanning?
Getting prompted for verification code but where do I put it in?
How do living politicians protect their readily obtainable signatures from misuse?
Value assignment between Series using .loc, same size with different indices
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!What is the difference between old style and new style classes in Python?Is there a difference between “==” and “is”?What is the difference between @staticmethod and @classmethod?Difference between append vs. extend list methods in PythonWhat's the difference between lists and tuples?Difference between __str__ and __repr__?What are the differences between type() and isinstance()?What is the difference between dict.items() and dict.iteritems()?How are iloc, ix and loc different?pandas: Assign values to a slice a MultiIndex by range of secondary index
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have an issue where I have two series of equal size but with different indices. I want to set one series equal to the other. This can be done by resetting the index, but in this case, I am using .loc
to slice a DataFrame to a Series.
Setup
Let's say I have a data frame:
df = pd.DataFrame('name': ['a', 'b', 'a', 'b'],
'num': [1, 1, 2, 2],
'val': None)
name num val
0 a 1 None
1 b 1 None
2 a 2 None
3 b 2 None
And two Series with values:
vals_a = pd.Series([21,32])
vals_b = pd.Series([43,54])
Desired Outcome
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
My Code
df.loc[df.name == 'a', 'vals'] = vals_a
df.loc[df.name == 'b', 'vals'] = vals_b
name num val vals
0 a 1 None 21.0
1 b 1 None 54.0
2 a 2 None NaN
3 b 2 None NaN
This is a simplified version of my problem. In reality, vals_a
and vals_b
are slices of a separate DataFrame with variable indices. How do I slice this so my original DataFrame stores the values in the smaller Series?
python pandas
add a comment |
I have an issue where I have two series of equal size but with different indices. I want to set one series equal to the other. This can be done by resetting the index, but in this case, I am using .loc
to slice a DataFrame to a Series.
Setup
Let's say I have a data frame:
df = pd.DataFrame('name': ['a', 'b', 'a', 'b'],
'num': [1, 1, 2, 2],
'val': None)
name num val
0 a 1 None
1 b 1 None
2 a 2 None
3 b 2 None
And two Series with values:
vals_a = pd.Series([21,32])
vals_b = pd.Series([43,54])
Desired Outcome
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
My Code
df.loc[df.name == 'a', 'vals'] = vals_a
df.loc[df.name == 'b', 'vals'] = vals_b
name num val vals
0 a 1 None 21.0
1 b 1 None 54.0
2 a 2 None NaN
3 b 2 None NaN
This is a simplified version of my problem. In reality, vals_a
and vals_b
are slices of a separate DataFrame with variable indices. How do I slice this so my original DataFrame stores the values in the smaller Series?
python pandas
add a comment |
I have an issue where I have two series of equal size but with different indices. I want to set one series equal to the other. This can be done by resetting the index, but in this case, I am using .loc
to slice a DataFrame to a Series.
Setup
Let's say I have a data frame:
df = pd.DataFrame('name': ['a', 'b', 'a', 'b'],
'num': [1, 1, 2, 2],
'val': None)
name num val
0 a 1 None
1 b 1 None
2 a 2 None
3 b 2 None
And two Series with values:
vals_a = pd.Series([21,32])
vals_b = pd.Series([43,54])
Desired Outcome
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
My Code
df.loc[df.name == 'a', 'vals'] = vals_a
df.loc[df.name == 'b', 'vals'] = vals_b
name num val vals
0 a 1 None 21.0
1 b 1 None 54.0
2 a 2 None NaN
3 b 2 None NaN
This is a simplified version of my problem. In reality, vals_a
and vals_b
are slices of a separate DataFrame with variable indices. How do I slice this so my original DataFrame stores the values in the smaller Series?
python pandas
I have an issue where I have two series of equal size but with different indices. I want to set one series equal to the other. This can be done by resetting the index, but in this case, I am using .loc
to slice a DataFrame to a Series.
Setup
Let's say I have a data frame:
df = pd.DataFrame('name': ['a', 'b', 'a', 'b'],
'num': [1, 1, 2, 2],
'val': None)
name num val
0 a 1 None
1 b 1 None
2 a 2 None
3 b 2 None
And two Series with values:
vals_a = pd.Series([21,32])
vals_b = pd.Series([43,54])
Desired Outcome
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
My Code
df.loc[df.name == 'a', 'vals'] = vals_a
df.loc[df.name == 'b', 'vals'] = vals_b
name num val vals
0 a 1 None 21.0
1 b 1 None 54.0
2 a 2 None NaN
3 b 2 None NaN
This is a simplified version of my problem. In reality, vals_a
and vals_b
are slices of a separate DataFrame with variable indices. How do I slice this so my original DataFrame stores the values in the smaller Series?
python pandas
python pandas
asked Mar 8 at 21:57
Cilantro DitrekCilantro Ditrek
1941318
1941318
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
pandas
is index
sensitive , which means when you assign
, beside the condition you mentioned within the loc
, it will still check the index
match or not
df.loc[df.name == 'a', 'vals'] = vals_a.values
df.loc[df.name == 'b', 'vals'] = vals_b.values
df
Out[964]:
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
add a comment |
The easiest method I can think of is to use map
with a dict of iterators:
iter_a, iter_b = (iter(v) for v in (vals_a, vals_b))
mapping = 'a': iter_a, 'b': iter_b
df['name'].map(lambda x: next(mapping[x]))
0 21
1 43
2 32
3 54
Name: name, dtype: int64
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%2f55071562%2fvalue-assignment-between-series-using-loc-same-size-with-different-indices%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
pandas
is index
sensitive , which means when you assign
, beside the condition you mentioned within the loc
, it will still check the index
match or not
df.loc[df.name == 'a', 'vals'] = vals_a.values
df.loc[df.name == 'b', 'vals'] = vals_b.values
df
Out[964]:
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
add a comment |
pandas
is index
sensitive , which means when you assign
, beside the condition you mentioned within the loc
, it will still check the index
match or not
df.loc[df.name == 'a', 'vals'] = vals_a.values
df.loc[df.name == 'b', 'vals'] = vals_b.values
df
Out[964]:
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
add a comment |
pandas
is index
sensitive , which means when you assign
, beside the condition you mentioned within the loc
, it will still check the index
match or not
df.loc[df.name == 'a', 'vals'] = vals_a.values
df.loc[df.name == 'b', 'vals'] = vals_b.values
df
Out[964]:
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
pandas
is index
sensitive , which means when you assign
, beside the condition you mentioned within the loc
, it will still check the index
match or not
df.loc[df.name == 'a', 'vals'] = vals_a.values
df.loc[df.name == 'b', 'vals'] = vals_b.values
df
Out[964]:
name num val vals
0 a 1 None 21.0
1 b 1 None 43.0
2 a 2 None 32.0
3 b 2 None 54.0
answered Mar 8 at 22:06
Wen-BenWen-Ben
127k83872
127k83872
add a comment |
add a comment |
The easiest method I can think of is to use map
with a dict of iterators:
iter_a, iter_b = (iter(v) for v in (vals_a, vals_b))
mapping = 'a': iter_a, 'b': iter_b
df['name'].map(lambda x: next(mapping[x]))
0 21
1 43
2 32
3 54
Name: name, dtype: int64
add a comment |
The easiest method I can think of is to use map
with a dict of iterators:
iter_a, iter_b = (iter(v) for v in (vals_a, vals_b))
mapping = 'a': iter_a, 'b': iter_b
df['name'].map(lambda x: next(mapping[x]))
0 21
1 43
2 32
3 54
Name: name, dtype: int64
add a comment |
The easiest method I can think of is to use map
with a dict of iterators:
iter_a, iter_b = (iter(v) for v in (vals_a, vals_b))
mapping = 'a': iter_a, 'b': iter_b
df['name'].map(lambda x: next(mapping[x]))
0 21
1 43
2 32
3 54
Name: name, dtype: int64
The easiest method I can think of is to use map
with a dict of iterators:
iter_a, iter_b = (iter(v) for v in (vals_a, vals_b))
mapping = 'a': iter_a, 'b': iter_b
df['name'].map(lambda x: next(mapping[x]))
0 21
1 43
2 32
3 54
Name: name, dtype: int64
answered Mar 8 at 22:05
cs95cs95
143k25164249
143k25164249
add a comment |
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%2f55071562%2fvalue-assignment-between-series-using-loc-same-size-with-different-indices%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