Search code examples
pythonpython-3.xpandasdataframedatareader

Merging list of 2 dataframes into one df with 2 columns


I have made this code that end up with a list of 2 dataframes, and a dataframe with the wrong content.

The DF created looks like this:

DATE    DEXDNUS DEXUSEU
2016-01-20  DEXDNUS nan
2016-01-21  DEXDNUS nan 
2016-01-22  DEXDNUS nan
2014-12-04  nan DEXUSEU
2014-12-05  nan DEXUSEU
2014-12-08  nan DEXUSEU

But what I need is the actual daily exrates instead of just the symbol for the currencies...

Something like this

DATE    DEXDNUS DEXUSEU
2014-12-04  6.78    1.24
2014-12-05  6.86    1.23
2014-12-08  6.81    1.27

How do I do this?

import pandas as pd
import pandas.io.data as web
import datetime

xratelist = ['DEXDNUS', 'DEXUSEU']
xrts = []

def xRateList_pd(xratelist, modus='trading',start=datetime.datetime(2000,1,1),end=pd.Timestamp.utcnow()):    

    years = 1.2
    days = int(252 * years)  # ant. arb. dage pr år = 252

    if modus == 'trading':
        end     = pd.Timestamp.utcnow()
        start   = end - days * pd.tseries.offsets.BDay()

    print('Fetching xratelist from Fred: ', xratelist)
    for xrt in xratelist:
        r = web.DataReader(xrt, 'fred',
                       start = start, end = end)
        # add a symbol column
        r[xrt] = xrt
        xrts.append(r)
    # concatenate all the dfs into one
    df_xrates = pd.concat(xrts)

    return df_xrates

if __name__ == '__main__':
    df_xrates = xRateList_pd(xratelist, modus='trading') 

Solution

  • Remove this part if you do not want symbol columns:

    # add a symbol column
    r[xrt] = xrt
    

    And pass axis='columns' to concat() if you want to concat along the columns axis:

    df_xrates = pd.concat(xrts, axis='columns')