【问题标题】:adding a dataframe to another dataframe under a specific column将数据框添加到特定列下的另一个数据框
【发布时间】:2022-01-03 10:44:51
【问题描述】:

我是 pandas 的新手,我一直坚持将数据帧的内容添加到另一个数据帧的任务。我正在使用返回数据框的 yfinance 库获取代码的历史数据

def get_fin_data(ticker):
  temp = mean_df[ticker].dropna()
  dates = [date.strftime("%Y-%m-%d") for date in temp.index.tolist()]
  start_end_dates = update_start_end_dates([dates[0], dates[-1]])
  data = yf.download(ticker, start=start_end_dates[0], end=start_end_dates[1])
  return data

for ticker in tickers:
  df_eod_price = get_fin_data(ticker)
  df_eod_price2 = df_eod_price.drop(['Open', 'High','Low','Close','Volume'], axis=1) # drop unwanted rows
  df_eod_price2['Returns'] = df_eod_price2['Adj Close']/df_eod_price2['Adj Close'].shift(1) - 1 # calculate daily returns  
  print(df_eod_price2.head())

我想将这些价格数据添加到我在以下数据框中拥有的相关代码中。

mean_df = df.groupby(['ticker', 'date']).mean()
print(mean_df)

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    如果您仍在寻找解决方案:

    我假设您的基本数据框 df_mean 看起来像:

                       compound
    ticker date                
    AMZN   2021-11-17         1
           2021-11-18         2
           2021-11-19         3
           2021-11-22         4
           2021-11-23         5
    FB     2021-11-22         1
           2021-11-23         2
    

    我还假设ticker 类似于包含股票代码字符串的列表:

    ticker = ["AMZN", "FB"]
    

    然后你可以这样做:

    dates = pd.to_datetime(df_mean.index.get_level_values("date"))
    start, end = dates.min().date(), (dates.max() + pd.Timedelta(days=1)).date()
    df = (
        yf.download(ticker, start=start, end=end)
          .stack(level=1)
          .drop(columns=["Close", "High", "Low", "Open", "Volume"])
          .rename(columns={"Adj Close": "returns"})
          .reorder_levels([1, 0])
          .sort_index(level=0)
    )
    df.index = df.index.rename(["ticker", "date"])
    

    这是一次下载,而不是每个股票一个。因此start/end 值基于date 列的min/max。 (这可能会下载比需要更多的数据。)

    结果如下:

                           returns
    ticker date                   
    AMZN   2021-11-17  3549.000000
           2021-11-18  3696.060059
           2021-11-19  3676.570068
           2021-11-22  3572.570068
           2021-11-23  3580.040039
    FB     2021-11-17   340.769989
           2021-11-18   338.690002
           2021-11-19   345.299988
           2021-11-22   341.010010
           2021-11-23   337.250000
    

    现在merge 的结果是df_mean

    df_mean = df_mean.merge(df, on=["ticker", "date"], how="left")
    

    或设置

    df_mean["returns"] = df.returns
    

    然后计算收益

    df_mean.returns = df_mean.groupby("ticker").returns.pct_change()
    

    结果df_mean

                       compound   returns
    ticker date                          
    AMZN   2021-11-17         1       NaN
           2021-11-18         2  0.041437
           2021-11-19         3 -0.005273
           2021-11-22         4 -0.028287
           2021-11-23         5  0.002091
    FB     2021-11-22         1       NaN
           2021-11-23         2 -0.011026
    

    【讨论】:

    • 你是个传奇!谢谢
    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 2021-12-13
    • 2016-11-15
    • 2020-12-09
    相关资源
    最近更新 更多