0

I have a dataframe that contains a column with values from 2016-10 to 2020-05 and looks like this:

rng = pd.date_range('2020-01', periods=5, freq='M')
df1 = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng)), 'Val2': ['a', 'b', 'c', 'd', 'e']}) 

                  Date       Val     Val2
             0 2020-01-31  0.921265    a
             1 2020-02-29  0.012289    b
             2 2020-03-31 -0.934321    c
             3 2020-04-30  0.134371    d
             4 2020-05-31 -1.373672    e

And another like this:

rng2 = pd.date_range('2020-07', periods=5, freq='M')
df2 = pd.DataFrame({ 'Date': rng2, 'Val' : np.random.randn(len(rng))})

                Date       Val
           0 2020-07-31  2.234768
           1 2020-08-31  1.308141
           2 2020-09-30 -0.603976
           3 2020-10-31 -0.316797
           4 2020-11-30  1.355123

How can I stack the Val from df2 under df1 so it looks like this:

              Date       Val     Val2
         0 2020-01-31  0.921265    a
         1 2020-02-29  0.012289    b
         2 2020-03-31 -0.934321    c
         3 2020-04-30  0.134371    d
         4 2020-05-31 -1.373672    e
         5 2020-07-31  2.234768   nan
         6 2020-08-31  1.308141   nan
         7 2020-09-30 -0.603976   nan
         8 2020-10-31 -0.316797   nan
         9 2020-11-30  1.355123   nan
AMC
  • 2,642
  • 7
  • 13
  • 35
  • ``pd.concat((df1, df2), ignore_index=True)`` ? – sammywemmy Jun 25 '20 at 21:42
  • Does this answer your question? [How do I combine two data frames?](https://stackoverflow.com/questions/12850345/how-do-i-combine-two-data-frames) – AMC Jun 25 '20 at 21:55
  • I'm not trying concat both dataframes, just stack one column from df2 under df1 – 5sWithCrackScreen Jun 25 '20 at 22:16
  • you could merge both of the dataframes with `df1.merge(df2, how = 'outer')` – PRIN Jun 25 '20 at 22:23
  • @PRIN I'm not trying to merge the dataframes, I'm trying to move one column from df2 under the column from df1. That doesn't give me what I'm looking for – 5sWithCrackScreen Jun 26 '20 at 12:08
  • @5sWithCrackScreen What do you mean by 'stack'? As sammywemmy says you should get your desired result if you do this - `pd.concat([df1, df2], ignore_index=True)`. – davidbilla Jun 27 '20 at 18:31

0 Answers0