【问题标题】:Pandas: how to adapt one dataframe to another based on the date?Pandas:如何根据日期将一个数据框调整为另一个数据框?
【发布时间】:2021-05-22 08:12:50
【问题描述】:

我有两个数据框,用于收集两种不同股票的历史价格序列。应用 describe() 我注意到第一只股票的元素是 1291,而第二只股票的元素是 1275。这种差异是由于这两种证券在不同的证券交易所上市,因此在某些日期显示出差异。我想做的是保留两个单独的数据帧,但确保在第一个数据帧中,删除第二个数据帧中不存在日期的所有行,以便两个数据帧完美匹配以执行分析。我读过有诸如merge()或join()之类的函数,但我无法很好地理解如何使用它们(如果这些是正确的函数)。感谢那些愿意花时间回答我问题的人。

"ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 1275 and the array at index 1 has size 1291"

谢谢

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pandas_datareader as web
from scipy import stats
import seaborn as sns
pd.options.display.min_rows= None
pd.options.display.max_rows= None

tickers = ['DISW.MI','IXJ','NRJ.PA','SGOL','VDC','VGT']
wts= [0.19,0.18,0.2,0.08,0.09,0.26]

price_data = web.get_data_yahoo(tickers,
                               start = '2016-01-01',
                               end = '2021-01-01')
price_data = price_data['Adj Close']

ret_data = price_data.pct_change()[1:]
port_ret = (ret_data * wts).sum(axis = 1)

benchmark_price = web.get_data_yahoo('ACWE.PA',
                               start = '2016-01-01',
                               end = '2021-01-01')
                               
benchmark_ret = benchmark_price["Adj Close"].pct_change()[1:].dropna()

#From now i get error

sns.regplot(benchmark_ret.values,
port_ret.values)
plt.xlabel("Benchmark Returns")
plt.ylabel("Portfolio Returns")
plt.title("Portfolio Returns vs Benchmark Returns")
plt.show()

(beta, alpha) = stats.linregress(benchmark_ret.values,
                port_ret.values)[0:2]
                
print("The portfolio beta is", round(beta, 4))

【问题讨论】:

    标签: python pandas dataframe stock mismatch


    【解决方案1】:

    让我们考虑一个玩具示例。

    df1 包含 6 天的数据,df2 包含 5 天的数据。

    据我所知,您希望 df1 也有 5 天的数据与 df2 的日期匹配。

    df1

    df1 = pd.DataFrame({
        'date':pd.date_range('2021-05-17', periods=6),
        'px':np.random.rand(6)
    })
    df1
        date        px
    0   2021-05-17  0.054907
    1   2021-05-18  0.192294
    2   2021-05-19  0.214051
    3   2021-05-20  0.623223
    4   2021-05-21  0.004627
    5   2021-05-22  0.127086
    

    df2

    df2 = pd.DataFrame({
        'date':pd.date_range('2021-05-17', periods=5),
        'px':np.random.rand(5)
    })
    df2
        date        px
    0   2021-05-17  0.650976
    1   2021-05-18  0.393061
    2   2021-05-19  0.985700
    3   2021-05-20  0.879786
    4   2021-05-21  0.463206
    

    代码 仅考虑 df2 中 df1 中的匹配日期。

    df1 = df1[df1.date.isin(df2.date)]
    

    输出df1

        date        px
    0   2021-05-17  0.054907
    1   2021-05-18  0.192294
    2   2021-05-19  0.214051
    3   2021-05-20  0.623223
    4   2021-05-21  0.004627
    

    【讨论】:

    • 非常感谢您的回复。此函数是否仅删除极端值或日期之间是否匹配?因为可能是不匹配的日期位于系列的中间。
    • 它与所有行的日期匹配,您会收到错误消息,因为您的 df 列名可能不是 date 而是其他名称。
    猜你喜欢
    • 2016-06-24
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多