1

So I have a dictionary with data frames: For example df[0]=

    Date         StockPrice
    01/01/2020   34.2
    01/02/2020   35
    01/03/2020   36
      ...

df[1]=

    Date        Rate    
   01/01/2020   4
   01/02/2020   5
   01/03/2020   5
   ...
 

df[2]=

   Date       High   Low 
   01/01/2020   45    42
   01/03/2020   45    40
   ...

df[3]=

Date         Rate2
01/01/2020    5 
01/03/2020    6

I want to merge all these dataframes on the date so it would look like this:

newdateframe=

Date          StockPrice     Rate    High   Low    Rate 2
01/02/2020     34.2          4       45     42     5
01/02/2020     35            5       NA     NA     NA
01/03/2020     36            5       45     40     6

I tried to do this: pd.concat(df.values(), ignore_index=True) but that doesn't work because it just puts each dataframe side by side and doesn't even capture all my dates. My dictionary has over 10 dataframes so I dont want to do a merge one by one I'd rather do something similar to the above code or a loop.

Michelle M
  • 63
  • 7

1 Answers1

0

Try:

pd.concat([d.set_index('Date') for d in df.values()], axis=1)

Output:

            StockPrice  Rate  High   Low  Rate2
01/01/2020        34.2     4  45.0  42.0    5.0
01/02/2020        35.0     5   NaN   NaN    NaN
01/03/2020        36.0     5  45.0  40.0    6.0
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74