Python: create new column and copy value from other row which is a swap of current row










2















I have a dataframe which has 3 columns:



import pandas as pd

d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

df = pd.DataFrame(d)


Dataframe looks like this:



 A B VALUE
left right 0
right left 1
east west 2
west east 3
south north 4
north south 5


I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.




Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:




 A B VALUE VALUE_2
left right 0 1
right left 1 0
east west 2 3
west east 3 2
south north 4 5
north south 5 4


I tried:



for row_num, record in df.iterrows():
A = df['A'][index]
B = df['B'][index]
if(pd.Series([record['A'] == B, record['B'] == A).all()):
df['VALUE_2'] = df['VALUE']


I'm struck here, inputs will be highly appreciated.










share|improve this question


























    2















    I have a dataframe which has 3 columns:



    import pandas as pd

    d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

    df = pd.DataFrame(d)


    Dataframe looks like this:



     A B VALUE
    left right 0
    right left 1
    east west 2
    west east 3
    south north 4
    north south 5


    I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.




    Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:




     A B VALUE VALUE_2
    left right 0 1
    right left 1 0
    east west 2 3
    west east 3 2
    south north 4 5
    north south 5 4


    I tried:



    for row_num, record in df.iterrows():
    A = df['A'][index]
    B = df['B'][index]
    if(pd.Series([record['A'] == B, record['B'] == A).all()):
    df['VALUE_2'] = df['VALUE']


    I'm struck here, inputs will be highly appreciated.










    share|improve this question
























      2












      2








      2








      I have a dataframe which has 3 columns:



      import pandas as pd

      d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

      df = pd.DataFrame(d)


      Dataframe looks like this:



       A B VALUE
      left right 0
      right left 1
      east west 2
      west east 3
      south north 4
      north south 5


      I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.




      Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:




       A B VALUE VALUE_2
      left right 0 1
      right left 1 0
      east west 2 3
      west east 3 2
      south north 4 5
      north south 5 4


      I tried:



      for row_num, record in df.iterrows():
      A = df['A'][index]
      B = df['B'][index]
      if(pd.Series([record['A'] == B, record['B'] == A).all()):
      df['VALUE_2'] = df['VALUE']


      I'm struck here, inputs will be highly appreciated.










      share|improve this question














      I have a dataframe which has 3 columns:



      import pandas as pd

      d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

      df = pd.DataFrame(d)


      Dataframe looks like this:



       A B VALUE
      left right 0
      right left 1
      east west 2
      west east 3
      south north 4
      north south 5


      I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.




      Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:




       A B VALUE VALUE_2
      left right 0 1
      right left 1 0
      east west 2 3
      west east 3 2
      south north 4 5
      north south 5 4


      I tried:



      for row_num, record in df.iterrows():
      A = df['A'][index]
      B = df['B'][index]
      if(pd.Series([record['A'] == B, record['B'] == A).all()):
      df['VALUE_2'] = df['VALUE']


      I'm struck here, inputs will be highly appreciated.







      python-3.x pandas






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 15 '18 at 7:10









      PokemonPokemon

      205




      205






















          2 Answers
          2






          active

          oldest

          votes


















          2














          Use map by Series:



          df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
          print (df)
          A B VALUE VALUE_2
          0 left right 0 1
          1 right left 1 0
          2 east west 2 3
          3 west east 3 2
          4 south north 4 5
          5 north south 5 4





          share|improve this answer























          • Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.

            – Pokemon
            Nov 15 '18 at 7:39











          • @Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?

            – jezrael
            Nov 15 '18 at 7:40











          • Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.

            – Pokemon
            Nov 15 '18 at 7:52






          • 1





            so need swap each value for each 2 rows groups? like df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?

            – jezrael
            Nov 15 '18 at 8:14






          • 1





            This looks perfect! ;)

            – Pokemon
            Nov 15 '18 at 9:50


















          1














          Just a more verbose answer:



          import pandas as pd

          d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

          df = pd.DataFrame(d)

          pdf = pd.DataFrame()
          for idx, item in df.iterrows():
          indx = list(df['B']).index(str(df['A'][idx]))
          pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)

          print(pdf)
          data = pd.concat([df, pdf], axis=1)
          print(data)





          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%2f53314127%2fpython-create-new-column-and-copy-value-from-other-row-which-is-a-swap-of-curre%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









            2














            Use map by Series:



            df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
            print (df)
            A B VALUE VALUE_2
            0 left right 0 1
            1 right left 1 0
            2 east west 2 3
            3 west east 3 2
            4 south north 4 5
            5 north south 5 4





            share|improve this answer























            • Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.

              – Pokemon
              Nov 15 '18 at 7:39











            • @Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?

              – jezrael
              Nov 15 '18 at 7:40











            • Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.

              – Pokemon
              Nov 15 '18 at 7:52






            • 1





              so need swap each value for each 2 rows groups? like df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?

              – jezrael
              Nov 15 '18 at 8:14






            • 1





              This looks perfect! ;)

              – Pokemon
              Nov 15 '18 at 9:50















            2














            Use map by Series:



            df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
            print (df)
            A B VALUE VALUE_2
            0 left right 0 1
            1 right left 1 0
            2 east west 2 3
            3 west east 3 2
            4 south north 4 5
            5 north south 5 4





            share|improve this answer























            • Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.

              – Pokemon
              Nov 15 '18 at 7:39











            • @Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?

              – jezrael
              Nov 15 '18 at 7:40











            • Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.

              – Pokemon
              Nov 15 '18 at 7:52






            • 1





              so need swap each value for each 2 rows groups? like df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?

              – jezrael
              Nov 15 '18 at 8:14






            • 1





              This looks perfect! ;)

              – Pokemon
              Nov 15 '18 at 9:50













            2












            2








            2







            Use map by Series:



            df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
            print (df)
            A B VALUE VALUE_2
            0 left right 0 1
            1 right left 1 0
            2 east west 2 3
            3 west east 3 2
            4 south north 4 5
            5 north south 5 4





            share|improve this answer













            Use map by Series:



            df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
            print (df)
            A B VALUE VALUE_2
            0 left right 0 1
            1 right left 1 0
            2 east west 2 3
            3 west east 3 2
            4 south north 4 5
            5 north south 5 4






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 15 '18 at 7:13









            jezraeljezrael

            345k25300371




            345k25300371












            • Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.

              – Pokemon
              Nov 15 '18 at 7:39











            • @Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?

              – jezrael
              Nov 15 '18 at 7:40











            • Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.

              – Pokemon
              Nov 15 '18 at 7:52






            • 1





              so need swap each value for each 2 rows groups? like df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?

              – jezrael
              Nov 15 '18 at 8:14






            • 1





              This looks perfect! ;)

              – Pokemon
              Nov 15 '18 at 9:50

















            • Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.

              – Pokemon
              Nov 15 '18 at 7:39











            • @Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?

              – jezrael
              Nov 15 '18 at 7:40











            • Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.

              – Pokemon
              Nov 15 '18 at 7:52






            • 1





              so need swap each value for each 2 rows groups? like df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?

              – jezrael
              Nov 15 '18 at 8:14






            • 1





              This looks perfect! ;)

              – Pokemon
              Nov 15 '18 at 9:50
















            Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.

            – Pokemon
            Nov 15 '18 at 7:39





            Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.

            – Pokemon
            Nov 15 '18 at 7:39













            @Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?

            – jezrael
            Nov 15 '18 at 7:40





            @Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?

            – jezrael
            Nov 15 '18 at 7:40













            Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.

            – Pokemon
            Nov 15 '18 at 7:52





            Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.

            – Pokemon
            Nov 15 '18 at 7:52




            1




            1





            so need swap each value for each 2 rows groups? like df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?

            – jezrael
            Nov 15 '18 at 8:14





            so need swap each value for each 2 rows groups? like df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?

            – jezrael
            Nov 15 '18 at 8:14




            1




            1





            This looks perfect! ;)

            – Pokemon
            Nov 15 '18 at 9:50





            This looks perfect! ;)

            – Pokemon
            Nov 15 '18 at 9:50













            1














            Just a more verbose answer:



            import pandas as pd

            d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

            df = pd.DataFrame(d)

            pdf = pd.DataFrame()
            for idx, item in df.iterrows():
            indx = list(df['B']).index(str(df['A'][idx]))
            pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)

            print(pdf)
            data = pd.concat([df, pdf], axis=1)
            print(data)





            share|improve this answer



























              1














              Just a more verbose answer:



              import pandas as pd

              d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

              df = pd.DataFrame(d)

              pdf = pd.DataFrame()
              for idx, item in df.iterrows():
              indx = list(df['B']).index(str(df['A'][idx]))
              pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)

              print(pdf)
              data = pd.concat([df, pdf], axis=1)
              print(data)





              share|improve this answer

























                1












                1








                1







                Just a more verbose answer:



                import pandas as pd

                d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

                df = pd.DataFrame(d)

                pdf = pd.DataFrame()
                for idx, item in df.iterrows():
                indx = list(df['B']).index(str(df['A'][idx]))
                pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)

                print(pdf)
                data = pd.concat([df, pdf], axis=1)
                print(data)





                share|improve this answer













                Just a more verbose answer:



                import pandas as pd

                d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]

                df = pd.DataFrame(d)

                pdf = pd.DataFrame()
                for idx, item in df.iterrows():
                indx = list(df['B']).index(str(df['A'][idx]))
                pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)

                print(pdf)
                data = pd.concat([df, pdf], axis=1)
                print(data)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 15 '18 at 7:53









                RussellBRussellB

                8191330




                8191330



























                    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%2f53314127%2fpython-create-new-column-and-copy-value-from-other-row-which-is-a-swap-of-curre%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







                    這個網誌中的熱門文章

                    What does pagestruct do in Eviews?

                    Dutch intervention in Lombok and Karangasem

                    Channel Islands