How to move values from one dataframe to another in pandas?How do I sort a dictionary by value?How to sort a dataframe by multiple column(s)?Add one row to pandas DataFrameSelecting multiple columns in a pandas dataframeAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrame by column nameHow to drop rows of Pandas DataFrame whose value in certain columns is NaNHow to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers

What is this high flying aircraft over Pennsylvania?

Magnifying glass in hyperbolic space

Asserting that Atheism and Theism are both faith based positions

categorizing a variable turns it from insignificant to significant

Make a Bowl of Alphabet Soup

Error in master's thesis, I do not know what to do

When is the exact date for EOL of Ubuntu 14.04 LTS?

"Marked down as someone wanting to sell shares." What does that mean?

How do I prevent inappropriate ads from appearing in my game?

Output visual diagram of picture

Highest stage count that are used one right after the other?

Capacitor electron flow

Why didn't Voldemort know what Grindelwald looked like?

How to test the sharpness of a knife?

Is there any common country to visit for persons holding UK and Schengen visas?

What is the purpose of using a decision tree?

Unfrosted light bulb

Why is implicit conversion not ambiguous for non-primitive types?

Why does a 97 / 92 key piano exist by Bosendorfer?

Do I have to take mana from my deck or hand when tapping this card?

Writing in a Christian voice

What should be the ideal length of sentences in a blog post for ease of reading?

How do you say "Trust your struggle." in French?

Started in 1987 vs. Starting in 1987



How to move values from one dataframe to another in pandas?


How do I sort a dictionary by value?How to sort a dataframe by multiple column(s)?Add one row to pandas DataFrameSelecting multiple columns in a pandas dataframeAdding new column to existing DataFrame in Python pandasDelete column from pandas DataFrame by column nameHow to drop rows of Pandas DataFrame whose value in certain columns is NaNHow to iterate over rows in a DataFrame in Pandas?Select rows from a DataFrame based on values in a column in pandasGet list from pandas DataFrame column headers













2















I have a df1 that looks like this:



 Symbol Order Shares
Date
2009-01-14 AAPL BUY 150
2009-01-21 AAPL SELL 150
2009-01-21 IBM BUY 400


And df2 looks like this:



 GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN NaN NaN NaN NaN
2009-01-21 NaN NaN NaN NaN NaN


I want to move the values in the first DF to the second so that the amount of shares populates under the appropriate stock symbol. So the above would look like:



 GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN 150 NaN NaN NaN
2009-01-21 NaN -150 NaN 400 NaN


How would I move all values that I have in my first dataframe to the second dataframe?










share|improve this question
























  • Are you just looking to pivot or actually fill data in another dataframe?: df.pivot(None, 'Symbol', 'Shares')

    – Chris
    Mar 7 at 20:28












  • What if a company has BUY and SELL on the same day?

    – coldspeed
    Mar 7 at 20:28











  • @Chris actually fill it.

    – Nerblo
    Mar 7 at 20:30











  • @coldspeed that's a good point, there shoudl actually be only a single line for that in the second df. I am going to edit now .

    – Nerblo
    Mar 7 at 20:30















2















I have a df1 that looks like this:



 Symbol Order Shares
Date
2009-01-14 AAPL BUY 150
2009-01-21 AAPL SELL 150
2009-01-21 IBM BUY 400


And df2 looks like this:



 GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN NaN NaN NaN NaN
2009-01-21 NaN NaN NaN NaN NaN


I want to move the values in the first DF to the second so that the amount of shares populates under the appropriate stock symbol. So the above would look like:



 GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN 150 NaN NaN NaN
2009-01-21 NaN -150 NaN 400 NaN


How would I move all values that I have in my first dataframe to the second dataframe?










share|improve this question
























  • Are you just looking to pivot or actually fill data in another dataframe?: df.pivot(None, 'Symbol', 'Shares')

    – Chris
    Mar 7 at 20:28












  • What if a company has BUY and SELL on the same day?

    – coldspeed
    Mar 7 at 20:28











  • @Chris actually fill it.

    – Nerblo
    Mar 7 at 20:30











  • @coldspeed that's a good point, there shoudl actually be only a single line for that in the second df. I am going to edit now .

    – Nerblo
    Mar 7 at 20:30













2












2








2








I have a df1 that looks like this:



 Symbol Order Shares
Date
2009-01-14 AAPL BUY 150
2009-01-21 AAPL SELL 150
2009-01-21 IBM BUY 400


And df2 looks like this:



 GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN NaN NaN NaN NaN
2009-01-21 NaN NaN NaN NaN NaN


I want to move the values in the first DF to the second so that the amount of shares populates under the appropriate stock symbol. So the above would look like:



 GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN 150 NaN NaN NaN
2009-01-21 NaN -150 NaN 400 NaN


How would I move all values that I have in my first dataframe to the second dataframe?










share|improve this question
















I have a df1 that looks like this:



 Symbol Order Shares
Date
2009-01-14 AAPL BUY 150
2009-01-21 AAPL SELL 150
2009-01-21 IBM BUY 400


And df2 looks like this:



 GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN NaN NaN NaN NaN
2009-01-21 NaN NaN NaN NaN NaN


I want to move the values in the first DF to the second so that the amount of shares populates under the appropriate stock symbol. So the above would look like:



 GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN 150 NaN NaN NaN
2009-01-21 NaN -150 NaN 400 NaN


How would I move all values that I have in my first dataframe to the second dataframe?







python pandas dataframe






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 20:31







Nerblo

















asked Mar 7 at 20:18









NerbloNerblo

308




308












  • Are you just looking to pivot or actually fill data in another dataframe?: df.pivot(None, 'Symbol', 'Shares')

    – Chris
    Mar 7 at 20:28












  • What if a company has BUY and SELL on the same day?

    – coldspeed
    Mar 7 at 20:28











  • @Chris actually fill it.

    – Nerblo
    Mar 7 at 20:30











  • @coldspeed that's a good point, there shoudl actually be only a single line for that in the second df. I am going to edit now .

    – Nerblo
    Mar 7 at 20:30

















  • Are you just looking to pivot or actually fill data in another dataframe?: df.pivot(None, 'Symbol', 'Shares')

    – Chris
    Mar 7 at 20:28












  • What if a company has BUY and SELL on the same day?

    – coldspeed
    Mar 7 at 20:28











  • @Chris actually fill it.

    – Nerblo
    Mar 7 at 20:30











  • @coldspeed that's a good point, there shoudl actually be only a single line for that in the second df. I am going to edit now .

    – Nerblo
    Mar 7 at 20:30
















Are you just looking to pivot or actually fill data in another dataframe?: df.pivot(None, 'Symbol', 'Shares')

– Chris
Mar 7 at 20:28






Are you just looking to pivot or actually fill data in another dataframe?: df.pivot(None, 'Symbol', 'Shares')

– Chris
Mar 7 at 20:28














What if a company has BUY and SELL on the same day?

– coldspeed
Mar 7 at 20:28





What if a company has BUY and SELL on the same day?

– coldspeed
Mar 7 at 20:28













@Chris actually fill it.

– Nerblo
Mar 7 at 20:30





@Chris actually fill it.

– Nerblo
Mar 7 at 20:30













@coldspeed that's a good point, there shoudl actually be only a single line for that in the second df. I am going to edit now .

– Nerblo
Mar 7 at 20:30





@coldspeed that's a good point, there shoudl actually be only a single line for that in the second df. I am going to edit now .

– Nerblo
Mar 7 at 20:30












2 Answers
2






active

oldest

votes


















1














You really don't need df2 here. You can compute the result directly from df using some simple reshaping functions set_index, unstack and reindex. You just need the symbols list.



(df.assign(Shares=np.where(df.Order == 'BUY', df.Shares, -df.Shares))
.drop('Order', 1)
.set_index('Symbol', append=True)['Shares']
.unstack(1)
.reindex(df2.columns, axis=1)) # you can replace df2.columns with a list

GOOG AAPL XOM IBM Cash
Date
2009-01-14 NaN 150.0 NaN NaN NaN
2009-01-21 NaN -150.0 NaN 400.0 NaN





share|improve this answer






























    1














    Use np.select to convert numbers to negative if Order == 'SELL' then update



    df['Shares'] = np.select([df['Order'] == 'SELL'], [-df['Shares']], df['Shares'])
    df2.update(df.pivot(None, 'Symbol', 'Shares'))


    GOOG AAPL XOM IBM Cash
    Date
    2009-01-14 NaN 150.0 NaN NaN NaN
    2009-01-21 NaN -150.0 NaN 400.0 NaN





    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%2f55052168%2fhow-to-move-values-from-one-dataframe-to-another-in-pandas%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









      1














      You really don't need df2 here. You can compute the result directly from df using some simple reshaping functions set_index, unstack and reindex. You just need the symbols list.



      (df.assign(Shares=np.where(df.Order == 'BUY', df.Shares, -df.Shares))
      .drop('Order', 1)
      .set_index('Symbol', append=True)['Shares']
      .unstack(1)
      .reindex(df2.columns, axis=1)) # you can replace df2.columns with a list

      GOOG AAPL XOM IBM Cash
      Date
      2009-01-14 NaN 150.0 NaN NaN NaN
      2009-01-21 NaN -150.0 NaN 400.0 NaN





      share|improve this answer



























        1














        You really don't need df2 here. You can compute the result directly from df using some simple reshaping functions set_index, unstack and reindex. You just need the symbols list.



        (df.assign(Shares=np.where(df.Order == 'BUY', df.Shares, -df.Shares))
        .drop('Order', 1)
        .set_index('Symbol', append=True)['Shares']
        .unstack(1)
        .reindex(df2.columns, axis=1)) # you can replace df2.columns with a list

        GOOG AAPL XOM IBM Cash
        Date
        2009-01-14 NaN 150.0 NaN NaN NaN
        2009-01-21 NaN -150.0 NaN 400.0 NaN





        share|improve this answer

























          1












          1








          1







          You really don't need df2 here. You can compute the result directly from df using some simple reshaping functions set_index, unstack and reindex. You just need the symbols list.



          (df.assign(Shares=np.where(df.Order == 'BUY', df.Shares, -df.Shares))
          .drop('Order', 1)
          .set_index('Symbol', append=True)['Shares']
          .unstack(1)
          .reindex(df2.columns, axis=1)) # you can replace df2.columns with a list

          GOOG AAPL XOM IBM Cash
          Date
          2009-01-14 NaN 150.0 NaN NaN NaN
          2009-01-21 NaN -150.0 NaN 400.0 NaN





          share|improve this answer













          You really don't need df2 here. You can compute the result directly from df using some simple reshaping functions set_index, unstack and reindex. You just need the symbols list.



          (df.assign(Shares=np.where(df.Order == 'BUY', df.Shares, -df.Shares))
          .drop('Order', 1)
          .set_index('Symbol', append=True)['Shares']
          .unstack(1)
          .reindex(df2.columns, axis=1)) # you can replace df2.columns with a list

          GOOG AAPL XOM IBM Cash
          Date
          2009-01-14 NaN 150.0 NaN NaN NaN
          2009-01-21 NaN -150.0 NaN 400.0 NaN






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 20:39









          coldspeedcoldspeed

          137k23148235




          137k23148235























              1














              Use np.select to convert numbers to negative if Order == 'SELL' then update



              df['Shares'] = np.select([df['Order'] == 'SELL'], [-df['Shares']], df['Shares'])
              df2.update(df.pivot(None, 'Symbol', 'Shares'))


              GOOG AAPL XOM IBM Cash
              Date
              2009-01-14 NaN 150.0 NaN NaN NaN
              2009-01-21 NaN -150.0 NaN 400.0 NaN





              share|improve this answer



























                1














                Use np.select to convert numbers to negative if Order == 'SELL' then update



                df['Shares'] = np.select([df['Order'] == 'SELL'], [-df['Shares']], df['Shares'])
                df2.update(df.pivot(None, 'Symbol', 'Shares'))


                GOOG AAPL XOM IBM Cash
                Date
                2009-01-14 NaN 150.0 NaN NaN NaN
                2009-01-21 NaN -150.0 NaN 400.0 NaN





                share|improve this answer

























                  1












                  1








                  1







                  Use np.select to convert numbers to negative if Order == 'SELL' then update



                  df['Shares'] = np.select([df['Order'] == 'SELL'], [-df['Shares']], df['Shares'])
                  df2.update(df.pivot(None, 'Symbol', 'Shares'))


                  GOOG AAPL XOM IBM Cash
                  Date
                  2009-01-14 NaN 150.0 NaN NaN NaN
                  2009-01-21 NaN -150.0 NaN 400.0 NaN





                  share|improve this answer













                  Use np.select to convert numbers to negative if Order == 'SELL' then update



                  df['Shares'] = np.select([df['Order'] == 'SELL'], [-df['Shares']], df['Shares'])
                  df2.update(df.pivot(None, 'Symbol', 'Shares'))


                  GOOG AAPL XOM IBM Cash
                  Date
                  2009-01-14 NaN 150.0 NaN NaN NaN
                  2009-01-21 NaN -150.0 NaN 400.0 NaN






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 7 at 20:39









                  ChrisChris

                  3,0982523




                  3,0982523



























                      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%2f55052168%2fhow-to-move-values-from-one-dataframe-to-another-in-pandas%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

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page