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;








1















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?










share|improve this question




























    1















    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?










    share|improve this question
























      1












      1








      1








      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?










      share|improve this question














      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 21:57









      Cilantro DitrekCilantro Ditrek

      1941318




      1941318






















          2 Answers
          2






          active

          oldest

          votes


















          4














          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





          share|improve this answer






























            1














            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





            share|improve this answer























              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%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









              4














              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





              share|improve this answer



























                4














                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





                share|improve this answer

























                  4












                  4








                  4







                  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





                  share|improve this answer













                  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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 8 at 22:06









                  Wen-BenWen-Ben

                  127k83872




                  127k83872























                      1














                      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





                      share|improve this answer



























                        1














                        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





                        share|improve this answer

























                          1












                          1








                          1







                          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





                          share|improve this answer













                          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






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 8 at 22:05









                          cs95cs95

                          143k25164249




                          143k25164249



























                              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%2f55071562%2fvalue-assignment-between-series-using-loc-same-size-with-different-indices%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

                              Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                              Compiling GNU Global with universal-ctags support 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!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                              Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved