python - 将开始日期和结束日期的数据框透视到真值表中

标签 python pandas

我有一个 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 成分股列表。假设您的数据帧的 startending 已经为 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/

相关文章:

python - 调试并行 Python 程序 (mpi4py)

python - 使用相同的 Id,pandas 从多个列表创建多行

python - Django 如何制作数据透视表?

python - 根据日期条件创建列,但出现此错误 AttributeError : 'SeriesGroupBy' object has no attribute 'sub' ?

Python 无法在位置 0 : character maps to <undefined> 处编码字符 '\u3010'

python - 使用列表时的排序问题

python - 在python中使用未指定的加密 key 解码加密文本

python - 如何在进程之间共享一个类?

python - Pandas MultiIndex 分层列的选择

python - 如何在 Pandas 中创建 groupby 子图?