簡體   English   中英

如何合並兩個具有不同行大小的數據框?

[英]How to combine two dataframe with different sizes of row?

因此,當我嘗試放置不同大小的數據框時,總是會導致錯誤。

import pandas as pd
from pandas import Series,DataFrame
import numpy as np

# For reading stock data from yahoo
import pandas_datareader as web

# For time stamps
from datetime import datetime

closing_df = web.DataReader(['AAPL','GOOG','MSFT','AMZN'],'yahoo',start,end)['Adj Close']
#when I do this, it is fine since the size are the same whereas
closing_df = web.DataReader(['AAPL','GOOG','MSFT','AMZN','BTC-USD'],'yahoo',start,end)['Adj Close']
#I always get this error
#ValueError: Index contains duplicate entries, cannot reshape

我試圖有兩個數據框,一個用於技術公司,一個用於BTC-USD,但是當我使用join,concat或merge時,似乎都沒有用,我想獲取兩個數據集的所有聯合日期並將其放在一起,例如如果兩個數據框都具有2010-11-30,則它將位於數據框中,但如果只有一個數據框包含該日期,則它將忽略或不將其放入聯合數據框中。 多謝

一種解決方法如下

tech = web.DataReader(['AAPL','GOOG','MSFT','AMZN'],'yahoo', start, end)['Adj Close']
btc = web.DataReader('BTC-USD','yahoo', start, end)['Adj Close']

result_df = pd.merge(tech, btc, left_index=True, right_index=True).rename(columns={'Adj Close': 'BTC'})

但是,通過檢查單個DataFrames可以看到,雖然技術僅具有財務日,但BTC也具有周末和假日,因此它們總體上檢索不同的日期。 使用上述聯接,您將丟失BTC數據。 也許最好先進行外部聯接,然后填寫值:

result_df = pd.merge(tech, btc, left_index=True, right_index=True,
                     how='outer').rename(columns={'Adj Close': 'BTC'})
result_df.fillna(method='ffill', inplace=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM