如何使用函数合并DataFrame?

时间:2015-08-06 17:47:33

标签: python pandas dataframe

我正在尝试合并股票价格的DataFrames与不同的开始日期。我的问题是,如何将DataFrame与我的占位符DataFrame合并?

stocks = {'xom': '2015-01-01', 'aapl': '2014-01-01', 'dvn': '2013-01-01'}

def stockAlert(x,y):
    price = web.get_data_yahoo(x,y)['Adj Close']
    dfNew = pd.DataFrame(price)
    addToDataFrame(dfNew)

def addToDataFrame(newDF):
    df2 = dfNew.append(newDF)

1 个答案:

答案 0 :(得分:1)

您可以先创建一个数据框列表,然后立即将它们连接起来。

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

stocks = {'xom': '2015-01-01', 'aapl': '2014-01-01', 'dvn': '2013-01-01'}

def fetch_data_from_yahoo(d_stocks):
    df_list = []
    for symbol, start_date in d_stocks.items():
        df_list.append(web.get_data_yahoo(symbol, start_date)['Adj Close'])
    return pd.concat(df_list, keys=list(d_stocks.keys()))

fetch_data_from_yahoo(stocks)

      Date      
dvn   2013-01-02     50.5433
      2013-01-03     51.4393
      2013-01-04     52.5858
      2013-01-07     52.6051
      2013-01-08     52.2293
      2013-01-09     51.4007
      2013-01-10     51.9114
      2013-01-11     52.2775
                      ...   
aapl  2015-07-27    122.7700
      2015-07-28    123.3800
      2015-07-29    122.9900
      2015-07-30    122.3700
      2015-07-31    121.3000
      2015-08-03    118.4400
      2015-08-04    114.6400
      2015-08-05    115.4000
Name: Adj Close, dtype: float64


fetch_data_from_yahoo(stocks).unstack(0)

                dvn    xom    aapl
Date                              
2013-01-02  50.5433    NaN     NaN
2013-01-03  51.4393    NaN     NaN
2013-01-04  52.5858    NaN     NaN
2013-01-07  52.6051    NaN     NaN
2013-01-08  52.2293    NaN     NaN
2013-01-09  51.4007    NaN     NaN
2013-01-10  51.9114    NaN     NaN
2013-01-11  52.2775    NaN     NaN
...             ...    ...     ...
2015-07-27  48.8300  79.26  122.77
2015-07-28  49.9900  82.48  123.38
2015-07-29  51.1800  83.14  122.99
2015-07-30  50.6100  83.01  122.37
2015-07-31  49.4200  79.21  121.30
2015-08-03  48.3600  78.06  118.44
2015-08-04  48.7400  77.17  114.64
2015-08-05  46.9500  77.17  115.40

[653 rows x 3 columns]