我有一个 Pandas DataFrame,其中包含 SP500 成分股添加到索引/从索引中删除的日期。它看起来像这样:
PERMNO start ending
0 10006.0 1957-03-01 1984-07-18
1 10030.0 1957-03-01 1969-01-08
2 10049.0 1925-12-31 1932-10-01
3 10057.0 1957-03-01 1992-07-02
4 10078.0 1992-08-20 2010-01-28
我还有一个我关心的日期列表,它包含 2003 年 1 月 1 日到 2009 年 6 月 30 日之间的交易日。我想创建一个数据框,其中索引上的这些日期和 PERMNO 作为列。它将被填充为该股票当天是否包含在 SP500 中的真值表。
有没有快速的方法来做到这一点?
注意:一些股票被添加到 SP500 中,然后被删除,然后再次添加。
最佳答案
如果我理解正确的话,您正在尝试查找一系列日期的 S&P 500 成分股列表。假设您的数据帧的 start
和 ending
已经为 datetime64
:
# the list of dates that you are interested in
dates = pd.Series(['1960-01-01', '1980-01-01'], dtype='datetime64[ns]')
start = df['start'].values
end = df['ending'].values
d = dates.values[:, None] # to prepare for array broadcasting
# if the date is between `start` and `ending` of the stock's membership in the S&P 500
match = (start <= d) & (d <= end)
# list of PERMNO for each as-of date
p = dates.index.to_series() \
.apply(lambda i: df.loc[match[i], 'PERMNO']) \
.stack().droplevel(-1)
# tying everything together
result = dates.to_frame('AsOfDate').join(p)
结果:
AsOfDate PERMNO
0 1960-01-01 10006.0
0 1960-01-01 10030.0
0 1960-01-01 10057.0
1 1980-01-01 10006.0
1 1980-01-01 10057.0
关于python - 将开始日期和结束日期的数据框透视到真值表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57237214/