Python - Swap values in multiple dataframes

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
6
down vote

favorite












I have a DataFrame like this



id val1 val2
0 A B
1 B B
2 A A
3 A A


And I would like swap values such as:



id val1 val2
0 B A
1 A A
2 B B
3 B B


I need to consider that the df could have other columns that I would like to keep unchanged.










share|improve this question

























    up vote
    6
    down vote

    favorite












    I have a DataFrame like this



    id val1 val2
    0 A B
    1 B B
    2 A A
    3 A A


    And I would like swap values such as:



    id val1 val2
    0 B A
    1 A A
    2 B B
    3 B B


    I need to consider that the df could have other columns that I would like to keep unchanged.










    share|improve this question























      up vote
      6
      down vote

      favorite









      up vote
      6
      down vote

      favorite











      I have a DataFrame like this



      id val1 val2
      0 A B
      1 B B
      2 A A
      3 A A


      And I would like swap values such as:



      id val1 val2
      0 B A
      1 A A
      2 B B
      3 B B


      I need to consider that the df could have other columns that I would like to keep unchanged.










      share|improve this question













      I have a DataFrame like this



      id val1 val2
      0 A B
      1 B B
      2 A A
      3 A A


      And I would like swap values such as:



      id val1 val2
      0 B A
      1 A A
      2 B B
      3 B B


      I need to consider that the df could have other columns that I would like to keep unchanged.







      python pandas dataframe






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 1 hour ago









      EGM8686

      1294




      1294






















          5 Answers
          5






          active

          oldest

          votes

















          up vote
          4
          down vote













          You can use pd.DataFrame.applymap with a dictionary:



          d = 'B': 'A', 'A': 'B'

          df = df.applymap(d.get).fillna(df)

          print(df)

          id val1 val2
          0 0 B A
          1 1 A A
          2 2 B B
          3 3 B B


          For performance, in particular memory usage, you may wish to use categorical data:



          for col in df.columns[1:]:
          df[col] = df[col].astype('category')
          df[col] = df[col].cat.rename_categories(d)





          share|improve this answer



























            up vote
            4
            down vote













            Try stacking, mapping, and then unstacking:



            df[['val1', 'val2']] = (
            df[['val1', 'val2']].stack().map('B': 'A', 'A': 'B').unstack())

            df
            id val1 val2
            0 0 B A
            1 1 A A
            2 2 B B
            3 3 B B


            For a (much) faster solution, use a nested list comprehension.



            mapping = 'B': 'A', 'A': 'B'
            df[['val1', 'val2']] = [
            [mapping.get(x, x) for x in row] for row in df[['val1', 'val2']].values]

            df
            id val1 val2
            0 0 B A
            1 1 A A
            2 2 B B
            3 3 B B





            share|improve this answer





























              up vote
              4
              down vote













              You can swap two values efficiently using numpy.where. However, if there are more than two values, this method stops working.



              a = df[['val1', 'val2']].values
              df[['val1', 'val2']] = np.where(a=='A', 'B', 'A')




               id val1 val2
              0 0 B A
              1 1 A A
              2 2 B B
              3 3 B B



              To adapt this keep other values the same, you can use np.select:



              c1 = a=='A'
              c2 = a=='B'
              np.select([c1, c2], ['B', 'A'], a)





              share|improve this answer





























                up vote
                4
                down vote













                Use factorize and roll the corresponding values



                def swaparoo(col):
                i, r = col.factorize()
                return pd.Series(r[(i + 1) % len(r)], col.index)

                df[['id']].join(df[['val1', 'val2']].apply(swaparoo))

                id val1 val2
                0 0 B A
                1 1 A A
                2 2 B B
                3 3 B B



                Alternative gymnastics using the same function. This incorporates the whole dataframe into the factorization.



                df.set_index('id').stack().pipe(swaparoo).unstack().reset_index()



                Examples



                df = pd.DataFrame(dict(id=range(4), val1=[*'ABAA'], val2=[*'BBAA']))

                print(
                df,
                df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                sep='nn'
                )

                id val1 val2
                0 0 A B
                1 1 B B
                2 2 A A
                3 3 A A

                id val1 val2
                0 0 B A
                1 1 A A
                2 2 B B
                3 3 B B



                df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB']))

                print(
                df,
                df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                sep='nn'
                )

                id val1 val2
                0 0 A B
                1 1 A B
                2 2 A B
                3 3 A B

                id val1 val2
                0 0 B A
                1 1 B A
                2 2 B A
                3 3 B A



                df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB'], val3=[*'CCCC']))

                print(
                df,
                df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                sep='nn'
                )

                id val1 val2 val3
                0 0 A B C
                1 1 A B C
                2 2 A B C
                3 3 A B C

                id val1 val2 val3
                0 0 B C A
                1 1 B C A
                2 2 B C A
                3 3 B C A



                df = pd.DataFrame(dict(id=range(4), val1=[*'ABCD'], val2=[*'BCDA'], val3=[*'CDAB']))

                print(
                df,
                df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                sep='nn'
                )

                id val1 val2 val3
                0 0 A B C
                1 1 B C D
                2 2 C D A
                3 3 D A B

                id val1 val2 val3
                0 0 B C D
                1 1 C D A
                2 2 D A B
                3 3 A B C





                share|improve this answer


















                • 1




                  this remind me this question ;-) stackoverflow.com/questions/52506862/…
                  – Wen
                  1 hour ago










                • I thought of the same thing.
                  – piRSquared
                  1 hour ago

















                up vote
                4
                down vote













                Using replace : why we need a C here , check this



                df[['val1','val2']].replace('A':'C','B':'A','C':'B')
                Out[263]:
                val1 val2
                0 B A
                1 A A
                2 B B
                3 B B





                share|improve this answer


















                • 2




                  This is a funny way to go about it :). I once looked into that awful replace function... so needlessly complex the mind boggles. The docs have this "gem": You are encouraged to experiment and play with this method to gain intuition about how it works.
                  – jpp
                  1 hour ago











                • @jpp yep ,I am still waiting for them to fix the bug /;-(
                  – Wen
                  1 hour ago










                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',
                convertImagesToLinks: true,
                noModals: false,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                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%2f52973762%2fpython-swap-values-in-multiple-dataframes%23new-answer', 'question_page');

                );

                Post as a guest






























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                4
                down vote













                You can use pd.DataFrame.applymap with a dictionary:



                d = 'B': 'A', 'A': 'B'

                df = df.applymap(d.get).fillna(df)

                print(df)

                id val1 val2
                0 0 B A
                1 1 A A
                2 2 B B
                3 3 B B


                For performance, in particular memory usage, you may wish to use categorical data:



                for col in df.columns[1:]:
                df[col] = df[col].astype('category')
                df[col] = df[col].cat.rename_categories(d)





                share|improve this answer
























                  up vote
                  4
                  down vote













                  You can use pd.DataFrame.applymap with a dictionary:



                  d = 'B': 'A', 'A': 'B'

                  df = df.applymap(d.get).fillna(df)

                  print(df)

                  id val1 val2
                  0 0 B A
                  1 1 A A
                  2 2 B B
                  3 3 B B


                  For performance, in particular memory usage, you may wish to use categorical data:



                  for col in df.columns[1:]:
                  df[col] = df[col].astype('category')
                  df[col] = df[col].cat.rename_categories(d)





                  share|improve this answer






















                    up vote
                    4
                    down vote










                    up vote
                    4
                    down vote









                    You can use pd.DataFrame.applymap with a dictionary:



                    d = 'B': 'A', 'A': 'B'

                    df = df.applymap(d.get).fillna(df)

                    print(df)

                    id val1 val2
                    0 0 B A
                    1 1 A A
                    2 2 B B
                    3 3 B B


                    For performance, in particular memory usage, you may wish to use categorical data:



                    for col in df.columns[1:]:
                    df[col] = df[col].astype('category')
                    df[col] = df[col].cat.rename_categories(d)





                    share|improve this answer












                    You can use pd.DataFrame.applymap with a dictionary:



                    d = 'B': 'A', 'A': 'B'

                    df = df.applymap(d.get).fillna(df)

                    print(df)

                    id val1 val2
                    0 0 B A
                    1 1 A A
                    2 2 B B
                    3 3 B B


                    For performance, in particular memory usage, you may wish to use categorical data:



                    for col in df.columns[1:]:
                    df[col] = df[col].astype('category')
                    df[col] = df[col].cat.rename_categories(d)






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 1 hour ago









                    jpp

                    74.7k184390




                    74.7k184390






















                        up vote
                        4
                        down vote













                        Try stacking, mapping, and then unstacking:



                        df[['val1', 'val2']] = (
                        df[['val1', 'val2']].stack().map('B': 'A', 'A': 'B').unstack())

                        df
                        id val1 val2
                        0 0 B A
                        1 1 A A
                        2 2 B B
                        3 3 B B


                        For a (much) faster solution, use a nested list comprehension.



                        mapping = 'B': 'A', 'A': 'B'
                        df[['val1', 'val2']] = [
                        [mapping.get(x, x) for x in row] for row in df[['val1', 'val2']].values]

                        df
                        id val1 val2
                        0 0 B A
                        1 1 A A
                        2 2 B B
                        3 3 B B





                        share|improve this answer


























                          up vote
                          4
                          down vote













                          Try stacking, mapping, and then unstacking:



                          df[['val1', 'val2']] = (
                          df[['val1', 'val2']].stack().map('B': 'A', 'A': 'B').unstack())

                          df
                          id val1 val2
                          0 0 B A
                          1 1 A A
                          2 2 B B
                          3 3 B B


                          For a (much) faster solution, use a nested list comprehension.



                          mapping = 'B': 'A', 'A': 'B'
                          df[['val1', 'val2']] = [
                          [mapping.get(x, x) for x in row] for row in df[['val1', 'val2']].values]

                          df
                          id val1 val2
                          0 0 B A
                          1 1 A A
                          2 2 B B
                          3 3 B B





                          share|improve this answer
























                            up vote
                            4
                            down vote










                            up vote
                            4
                            down vote









                            Try stacking, mapping, and then unstacking:



                            df[['val1', 'val2']] = (
                            df[['val1', 'val2']].stack().map('B': 'A', 'A': 'B').unstack())

                            df
                            id val1 val2
                            0 0 B A
                            1 1 A A
                            2 2 B B
                            3 3 B B


                            For a (much) faster solution, use a nested list comprehension.



                            mapping = 'B': 'A', 'A': 'B'
                            df[['val1', 'val2']] = [
                            [mapping.get(x, x) for x in row] for row in df[['val1', 'val2']].values]

                            df
                            id val1 val2
                            0 0 B A
                            1 1 A A
                            2 2 B B
                            3 3 B B





                            share|improve this answer














                            Try stacking, mapping, and then unstacking:



                            df[['val1', 'val2']] = (
                            df[['val1', 'val2']].stack().map('B': 'A', 'A': 'B').unstack())

                            df
                            id val1 val2
                            0 0 B A
                            1 1 A A
                            2 2 B B
                            3 3 B B


                            For a (much) faster solution, use a nested list comprehension.



                            mapping = 'B': 'A', 'A': 'B'
                            df[['val1', 'val2']] = [
                            [mapping.get(x, x) for x in row] for row in df[['val1', 'val2']].values]

                            df
                            id val1 val2
                            0 0 B A
                            1 1 A A
                            2 2 B B
                            3 3 B B






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 1 hour ago

























                            answered 1 hour ago









                            coldspeed

                            108k1796166




                            108k1796166




















                                up vote
                                4
                                down vote













                                You can swap two values efficiently using numpy.where. However, if there are more than two values, this method stops working.



                                a = df[['val1', 'val2']].values
                                df[['val1', 'val2']] = np.where(a=='A', 'B', 'A')




                                 id val1 val2
                                0 0 B A
                                1 1 A A
                                2 2 B B
                                3 3 B B



                                To adapt this keep other values the same, you can use np.select:



                                c1 = a=='A'
                                c2 = a=='B'
                                np.select([c1, c2], ['B', 'A'], a)





                                share|improve this answer


























                                  up vote
                                  4
                                  down vote













                                  You can swap two values efficiently using numpy.where. However, if there are more than two values, this method stops working.



                                  a = df[['val1', 'val2']].values
                                  df[['val1', 'val2']] = np.where(a=='A', 'B', 'A')




                                   id val1 val2
                                  0 0 B A
                                  1 1 A A
                                  2 2 B B
                                  3 3 B B



                                  To adapt this keep other values the same, you can use np.select:



                                  c1 = a=='A'
                                  c2 = a=='B'
                                  np.select([c1, c2], ['B', 'A'], a)





                                  share|improve this answer
























                                    up vote
                                    4
                                    down vote










                                    up vote
                                    4
                                    down vote









                                    You can swap two values efficiently using numpy.where. However, if there are more than two values, this method stops working.



                                    a = df[['val1', 'val2']].values
                                    df[['val1', 'val2']] = np.where(a=='A', 'B', 'A')




                                     id val1 val2
                                    0 0 B A
                                    1 1 A A
                                    2 2 B B
                                    3 3 B B



                                    To adapt this keep other values the same, you can use np.select:



                                    c1 = a=='A'
                                    c2 = a=='B'
                                    np.select([c1, c2], ['B', 'A'], a)





                                    share|improve this answer














                                    You can swap two values efficiently using numpy.where. However, if there are more than two values, this method stops working.



                                    a = df[['val1', 'val2']].values
                                    df[['val1', 'val2']] = np.where(a=='A', 'B', 'A')




                                     id val1 val2
                                    0 0 B A
                                    1 1 A A
                                    2 2 B B
                                    3 3 B B



                                    To adapt this keep other values the same, you can use np.select:



                                    c1 = a=='A'
                                    c2 = a=='B'
                                    np.select([c1, c2], ['B', 'A'], a)






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited 1 hour ago

























                                    answered 1 hour ago









                                    user3483203

                                    27.2k72250




                                    27.2k72250




















                                        up vote
                                        4
                                        down vote













                                        Use factorize and roll the corresponding values



                                        def swaparoo(col):
                                        i, r = col.factorize()
                                        return pd.Series(r[(i + 1) % len(r)], col.index)

                                        df[['id']].join(df[['val1', 'val2']].apply(swaparoo))

                                        id val1 val2
                                        0 0 B A
                                        1 1 A A
                                        2 2 B B
                                        3 3 B B



                                        Alternative gymnastics using the same function. This incorporates the whole dataframe into the factorization.



                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index()



                                        Examples



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'ABAA'], val2=[*'BBAA']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2
                                        0 0 A B
                                        1 1 B B
                                        2 2 A A
                                        3 3 A A

                                        id val1 val2
                                        0 0 B A
                                        1 1 A A
                                        2 2 B B
                                        3 3 B B



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2
                                        0 0 A B
                                        1 1 A B
                                        2 2 A B
                                        3 3 A B

                                        id val1 val2
                                        0 0 B A
                                        1 1 B A
                                        2 2 B A
                                        3 3 B A



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB'], val3=[*'CCCC']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2 val3
                                        0 0 A B C
                                        1 1 A B C
                                        2 2 A B C
                                        3 3 A B C

                                        id val1 val2 val3
                                        0 0 B C A
                                        1 1 B C A
                                        2 2 B C A
                                        3 3 B C A



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'ABCD'], val2=[*'BCDA'], val3=[*'CDAB']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2 val3
                                        0 0 A B C
                                        1 1 B C D
                                        2 2 C D A
                                        3 3 D A B

                                        id val1 val2 val3
                                        0 0 B C D
                                        1 1 C D A
                                        2 2 D A B
                                        3 3 A B C





                                        share|improve this answer


















                                        • 1




                                          this remind me this question ;-) stackoverflow.com/questions/52506862/…
                                          – Wen
                                          1 hour ago










                                        • I thought of the same thing.
                                          – piRSquared
                                          1 hour ago














                                        up vote
                                        4
                                        down vote













                                        Use factorize and roll the corresponding values



                                        def swaparoo(col):
                                        i, r = col.factorize()
                                        return pd.Series(r[(i + 1) % len(r)], col.index)

                                        df[['id']].join(df[['val1', 'val2']].apply(swaparoo))

                                        id val1 val2
                                        0 0 B A
                                        1 1 A A
                                        2 2 B B
                                        3 3 B B



                                        Alternative gymnastics using the same function. This incorporates the whole dataframe into the factorization.



                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index()



                                        Examples



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'ABAA'], val2=[*'BBAA']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2
                                        0 0 A B
                                        1 1 B B
                                        2 2 A A
                                        3 3 A A

                                        id val1 val2
                                        0 0 B A
                                        1 1 A A
                                        2 2 B B
                                        3 3 B B



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2
                                        0 0 A B
                                        1 1 A B
                                        2 2 A B
                                        3 3 A B

                                        id val1 val2
                                        0 0 B A
                                        1 1 B A
                                        2 2 B A
                                        3 3 B A



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB'], val3=[*'CCCC']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2 val3
                                        0 0 A B C
                                        1 1 A B C
                                        2 2 A B C
                                        3 3 A B C

                                        id val1 val2 val3
                                        0 0 B C A
                                        1 1 B C A
                                        2 2 B C A
                                        3 3 B C A



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'ABCD'], val2=[*'BCDA'], val3=[*'CDAB']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2 val3
                                        0 0 A B C
                                        1 1 B C D
                                        2 2 C D A
                                        3 3 D A B

                                        id val1 val2 val3
                                        0 0 B C D
                                        1 1 C D A
                                        2 2 D A B
                                        3 3 A B C





                                        share|improve this answer


















                                        • 1




                                          this remind me this question ;-) stackoverflow.com/questions/52506862/…
                                          – Wen
                                          1 hour ago










                                        • I thought of the same thing.
                                          – piRSquared
                                          1 hour ago












                                        up vote
                                        4
                                        down vote










                                        up vote
                                        4
                                        down vote









                                        Use factorize and roll the corresponding values



                                        def swaparoo(col):
                                        i, r = col.factorize()
                                        return pd.Series(r[(i + 1) % len(r)], col.index)

                                        df[['id']].join(df[['val1', 'val2']].apply(swaparoo))

                                        id val1 val2
                                        0 0 B A
                                        1 1 A A
                                        2 2 B B
                                        3 3 B B



                                        Alternative gymnastics using the same function. This incorporates the whole dataframe into the factorization.



                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index()



                                        Examples



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'ABAA'], val2=[*'BBAA']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2
                                        0 0 A B
                                        1 1 B B
                                        2 2 A A
                                        3 3 A A

                                        id val1 val2
                                        0 0 B A
                                        1 1 A A
                                        2 2 B B
                                        3 3 B B



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2
                                        0 0 A B
                                        1 1 A B
                                        2 2 A B
                                        3 3 A B

                                        id val1 val2
                                        0 0 B A
                                        1 1 B A
                                        2 2 B A
                                        3 3 B A



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB'], val3=[*'CCCC']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2 val3
                                        0 0 A B C
                                        1 1 A B C
                                        2 2 A B C
                                        3 3 A B C

                                        id val1 val2 val3
                                        0 0 B C A
                                        1 1 B C A
                                        2 2 B C A
                                        3 3 B C A



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'ABCD'], val2=[*'BCDA'], val3=[*'CDAB']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2 val3
                                        0 0 A B C
                                        1 1 B C D
                                        2 2 C D A
                                        3 3 D A B

                                        id val1 val2 val3
                                        0 0 B C D
                                        1 1 C D A
                                        2 2 D A B
                                        3 3 A B C





                                        share|improve this answer














                                        Use factorize and roll the corresponding values



                                        def swaparoo(col):
                                        i, r = col.factorize()
                                        return pd.Series(r[(i + 1) % len(r)], col.index)

                                        df[['id']].join(df[['val1', 'val2']].apply(swaparoo))

                                        id val1 val2
                                        0 0 B A
                                        1 1 A A
                                        2 2 B B
                                        3 3 B B



                                        Alternative gymnastics using the same function. This incorporates the whole dataframe into the factorization.



                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index()



                                        Examples



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'ABAA'], val2=[*'BBAA']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2
                                        0 0 A B
                                        1 1 B B
                                        2 2 A A
                                        3 3 A A

                                        id val1 val2
                                        0 0 B A
                                        1 1 A A
                                        2 2 B B
                                        3 3 B B



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2
                                        0 0 A B
                                        1 1 A B
                                        2 2 A B
                                        3 3 A B

                                        id val1 val2
                                        0 0 B A
                                        1 1 B A
                                        2 2 B A
                                        3 3 B A



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'AAAA'], val2=[*'BBBB'], val3=[*'CCCC']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2 val3
                                        0 0 A B C
                                        1 1 A B C
                                        2 2 A B C
                                        3 3 A B C

                                        id val1 val2 val3
                                        0 0 B C A
                                        1 1 B C A
                                        2 2 B C A
                                        3 3 B C A



                                        df = pd.DataFrame(dict(id=range(4), val1=[*'ABCD'], val2=[*'BCDA'], val3=[*'CDAB']))

                                        print(
                                        df,
                                        df.set_index('id').stack().pipe(swaparoo).unstack().reset_index(),
                                        sep='nn'
                                        )

                                        id val1 val2 val3
                                        0 0 A B C
                                        1 1 B C D
                                        2 2 C D A
                                        3 3 D A B

                                        id val1 val2 val3
                                        0 0 B C D
                                        1 1 C D A
                                        2 2 D A B
                                        3 3 A B C






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited 1 hour ago

























                                        answered 1 hour ago









                                        piRSquared

                                        145k19127259




                                        145k19127259







                                        • 1




                                          this remind me this question ;-) stackoverflow.com/questions/52506862/…
                                          – Wen
                                          1 hour ago










                                        • I thought of the same thing.
                                          – piRSquared
                                          1 hour ago












                                        • 1




                                          this remind me this question ;-) stackoverflow.com/questions/52506862/…
                                          – Wen
                                          1 hour ago










                                        • I thought of the same thing.
                                          – piRSquared
                                          1 hour ago







                                        1




                                        1




                                        this remind me this question ;-) stackoverflow.com/questions/52506862/…
                                        – Wen
                                        1 hour ago




                                        this remind me this question ;-) stackoverflow.com/questions/52506862/…
                                        – Wen
                                        1 hour ago












                                        I thought of the same thing.
                                        – piRSquared
                                        1 hour ago




                                        I thought of the same thing.
                                        – piRSquared
                                        1 hour ago










                                        up vote
                                        4
                                        down vote













                                        Using replace : why we need a C here , check this



                                        df[['val1','val2']].replace('A':'C','B':'A','C':'B')
                                        Out[263]:
                                        val1 val2
                                        0 B A
                                        1 A A
                                        2 B B
                                        3 B B





                                        share|improve this answer


















                                        • 2




                                          This is a funny way to go about it :). I once looked into that awful replace function... so needlessly complex the mind boggles. The docs have this "gem": You are encouraged to experiment and play with this method to gain intuition about how it works.
                                          – jpp
                                          1 hour ago











                                        • @jpp yep ,I am still waiting for them to fix the bug /;-(
                                          – Wen
                                          1 hour ago














                                        up vote
                                        4
                                        down vote













                                        Using replace : why we need a C here , check this



                                        df[['val1','val2']].replace('A':'C','B':'A','C':'B')
                                        Out[263]:
                                        val1 val2
                                        0 B A
                                        1 A A
                                        2 B B
                                        3 B B





                                        share|improve this answer


















                                        • 2




                                          This is a funny way to go about it :). I once looked into that awful replace function... so needlessly complex the mind boggles. The docs have this "gem": You are encouraged to experiment and play with this method to gain intuition about how it works.
                                          – jpp
                                          1 hour ago











                                        • @jpp yep ,I am still waiting for them to fix the bug /;-(
                                          – Wen
                                          1 hour ago












                                        up vote
                                        4
                                        down vote










                                        up vote
                                        4
                                        down vote









                                        Using replace : why we need a C here , check this



                                        df[['val1','val2']].replace('A':'C','B':'A','C':'B')
                                        Out[263]:
                                        val1 val2
                                        0 B A
                                        1 A A
                                        2 B B
                                        3 B B





                                        share|improve this answer














                                        Using replace : why we need a C here , check this



                                        df[['val1','val2']].replace('A':'C','B':'A','C':'B')
                                        Out[263]:
                                        val1 val2
                                        0 B A
                                        1 A A
                                        2 B B
                                        3 B B






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited 1 hour ago

























                                        answered 1 hour ago









                                        Wen

                                        87.5k72653




                                        87.5k72653







                                        • 2




                                          This is a funny way to go about it :). I once looked into that awful replace function... so needlessly complex the mind boggles. The docs have this "gem": You are encouraged to experiment and play with this method to gain intuition about how it works.
                                          – jpp
                                          1 hour ago











                                        • @jpp yep ,I am still waiting for them to fix the bug /;-(
                                          – Wen
                                          1 hour ago












                                        • 2




                                          This is a funny way to go about it :). I once looked into that awful replace function... so needlessly complex the mind boggles. The docs have this "gem": You are encouraged to experiment and play with this method to gain intuition about how it works.
                                          – jpp
                                          1 hour ago











                                        • @jpp yep ,I am still waiting for them to fix the bug /;-(
                                          – Wen
                                          1 hour ago







                                        2




                                        2




                                        This is a funny way to go about it :). I once looked into that awful replace function... so needlessly complex the mind boggles. The docs have this "gem": You are encouraged to experiment and play with this method to gain intuition about how it works.
                                        – jpp
                                        1 hour ago





                                        This is a funny way to go about it :). I once looked into that awful replace function... so needlessly complex the mind boggles. The docs have this "gem": You are encouraged to experiment and play with this method to gain intuition about how it works.
                                        – jpp
                                        1 hour ago













                                        @jpp yep ,I am still waiting for them to fix the bug /;-(
                                        – Wen
                                        1 hour ago




                                        @jpp yep ,I am still waiting for them to fix the bug /;-(
                                        – Wen
                                        1 hour ago

















                                         

                                        draft saved


                                        draft discarded















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52973762%2fpython-swap-values-in-multiple-dataframes%23new-answer', 'question_page');

                                        );

                                        Post as a guest













































































                                        Comments

                                        Popular posts from this blog

                                        What does second last employer means? [closed]

                                        Installing NextGIS Connect into QGIS 3?

                                        One-line joke