我想合并两个具有完全相同列名的 DataFrame。重叠的列可以添加在一起。我遇到了一些麻烦,因为分组应该发生在名为“日期”的“索引”上,但我无法通过使用“日期”名称来创建该索引。实际上,我只需要指数(日期)和所有股票的“Adj Close”总和。我试过:data.join(temp, how='outer')返回: “ValueError:列重叠但未指定后缀:Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'], dtype='object')”data = pd.concat([data, temp]).groupby([data.index, temp.index], as_index=True).sum(axis=1)返回: “石斑鱼和轴的长度必须相同data = pd.merge(data, temp, left_index=True, right_index=True)['Adj Close'].sum(axis=1, skipna=True).astype(np.int64)返回: “KeyError:'调整关闭'”代码def overview(request): stocks = Stock.objects.all() data = None for stock in stocks: if data is None: data = yf.download(stock.ticker, start=stock.trade_date, period="ytd") else: temp = yf.download(stock.ticker, start=stock.trade_date, period="ytd") data.join(temp, how='outer')数据帧输出 1[*********************100%***********************] 1 of 1 completed Open High ... Adj Close VolumeDate ... 2019-09-19 55.502499 55.939999 ... 54.697304 882424002019-09-20 55.345001 55.639999 ... 53.897728 2216524002019-09-23 54.737499 54.959999 ... 54.142803 766620002019-09-24 55.257500 55.622501 ... 53.885353 1247632002019-09-25 54.637501 55.375000 ... 54.714626 87613600... ... ... ... ... ...2020-09-10 120.360001 120.500000 ... 113.489998 1822744002020-09-11 114.570000 115.230003 ... 112.000000 1808603002020-09-14 114.720001 115.930000 ... 115.360001 1401501002020-09-15 118.330002 118.830002 ... 115.540001 1846420002020-09-16 115.230003 116.000000 ... 112.129997 154679000[251 rows x 6 columns]
1 回答
慕婉清6462132
TA贡献1804条经验 获得超2个赞
假设你有 2 个这样的 df :
df1 = pd.DataFrame({'Adj Close':[1, 2]}, index=['2019-09-19','2019-09-20'])
df2 = pd.DataFrame({'Adj Close':[3, 4, 5]}, index=['2019-09-19','2019-09-20','2019-09-21'])
df1
Adj Close
2019-09-19 1
2019-09-20 2
df2
Adj Close
2019-09-19 3
2019-09-20 4
2019-09-21 5
然后你可以连接成一个 df:
df = pd.concat([df1, df2])
Adj Close
2019-09-19 1
2019-09-20 2
2019-09-19 3
2019-09-20 4
2019-09-21 5
并用 sum 进行 groupby:
result = df.groupby(df.index).sum()
Adj Close
2019-09-19 4
2019-09-20 6
2019-09-21 5
添加回答
举报
0/150
提交
取消